Friday 4 December 2015

C++ const explain

What does “const X* p” mean?

It means p points to an object of class X, but p can’t be used to change that X object (naturally p could also be NULL).
Read it right-to-left: “p is a pointer to an X that is constant.”
Or we can read it like only-read variable.

 

What’s the difference between “const X* p”, “X* const p” and “const X* const p”?

Read the pointer declarations right-to-left.
  • const X* p means “p points to an X that is const”: the X object can’t be changed via p.
  • X* const p means “p is a const pointer to an X that is non-const”: you can’t change the pointer p itself, but you can change the X object via p.
  • const X* const p means “p is a const pointer to an X that is const”: you can’t change the pointer p itself, nor can you change the X object via p.

 

What does “const & x” mean? 

It means x aliases an X object, but you can’t change that X object via x.
Read it right-to-left: “x is a reference to an X that is const.”



What do “X const& x” and “X const* p” mean? 

X const& x is equivalent to const X& x, and X const* x is equivalent to const X* x.

PS: Some people prefer the const-on-the-right style, calling it “consistent const.” Indeed the const-on-the-right style can be more consistent than the alternative: the const-on-the-right style always puts the const on the right of what it constifies, whereas the other style sometimes puts the const on the left and sometimes on the right.

For example:
if const is in front of * then const is used for the object which is pointed to, is const is bebind to *, like int** const p = &x, const is used for pointer itself, it means that pointer p is constancte, but the object is pointed by p isn't constante.
const在 * 前面则const修饰的是指针指向的对象,即指向的对象是只读的。如果const 在 *后面则修饰的是指针本身,即该指针变量不可指向其他对象,而指向的对象并不受const约束。

No comments:

Post a Comment