Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

c++ - const char* and char const* - are they the same?

From my understanding, const modifiers should be read from right to left. From that, I get that:

const char*

is a pointer whose char elements can't be modified, but the pointer itself can, and

char const*

is a constant pointer to mutable chars.

But I get the following errors for the following code:

const char* x = new char[20];
x = new char[30];   //this works, as expected
x[0] = 'a';         //gives an error as expected

char const* y = new char[20];
y = new char[20];   //this works, although the pointer should be const (right?)
y[0] = 'a';         //this doesn't although I expect it to work

So... which one is it? Is my understanding or my compiler(VS 2005) wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Actually, according to the standard, const modifies the element directly to its left. The use of const at the beginning of a declaration is just a convenient mental shortcut. So the following two statements are equivalent:

char const * pointerToConstantContent1;
const char * pointerToConstantContent2;

In order to ensure the pointer itself is not modified, const should be placed after the asterisk:

char * const constantPointerToMutableContent;

To protect both the pointer and the content to which it points, use two consts.

char const * const constantPointerToConstantContent;

I've personally adopted always putting the const after the portion I intend not to modify such that I maintain consistency even when the pointer is the part I wish to keep constant.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...