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 anX
that isconst
”: theX
object can’t be changed viap
.X* const p
means “p
is aconst
pointer to anX
that is non-const
”: you can’t change the pointerp
itself, but you can change theX
object viap
.const X* const p
means “p
is aconst
pointer to anX
that isconst
”: you can’t change the pointerp
itself, nor can you change theX
object viap
.
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
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
const在 * 前面则const修饰的是指针指向的对象,即指向的对象是只读的。如果const 在 *后面则修饰的是指针本身,即该指针变量不可指向其他对象,而指向的对象并不受const约束。
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