开发者

What is the difference between these two uses of const in C++? [duplicate]

This question already has answers here: 开发者_运维百科 Closed 12 years ago.

Possible Duplicate:

what is the difference between const int*, const int * const, int const *

What is the difference between

A const * pa2 = pa1;

and

A * const pa2 = pa1;

(I have some class A for example).


Read the type from right to left:

A const * pa2 = pa1;

pa2 is a pointer to a read-only A (the object may not be changed through the pointer)

A * const pa2 = pa1;

pa2 is a read-only pointer to A (the pointer may not be changed)

This does not mean that A cannot change (or is actually constant) const is misleading, understand it always as read-only. Other aliased pointers might modify A.


A const * pa2

This is a non-const pointer to a const A. You can change where the pointer points but you can't change the object pointed to by the pointer.

A * const pa2

This is a const pointer to a non-const A. You can't change where the pointer points but you can change the object pointed to by the pointer.

A const * const pa2

This is a const pointer to a const A. You can't change where the pointer points and you can't change the object pointed to by the pointer.

You may find the "Clockwise/Spiral Rule" helpful when trying to decipher declarations in C and C++.


It means that the first is a pointer to a const object, which (loosely) means the object can't be change.

The second is a const pointer to an object, which means the pointer itself can not be changed (ie assigned to a different object).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜