const char* 和 char const* - 它们是一样的吗?

2022-01-23 00:00:00 pointers constants c++

据我了解,const 修饰符应该从右到左阅读.从那,我明白了:

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

const char*

是一个指针,它的char元素不能修改,但指针本身可以,并且

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

char const*

是一个指向 mutable 字符的常量指针.

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

那么...是哪一个?是我的理解还是我的编译器(VS 2005)错了?

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

推荐答案

其实按照标准,const直接修改元素到它的左边.在声明的开头使用 const 只是一种方便的思维捷径.所以下面两条语句是等价的:

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;

为了保证指针本身不被修改,const应该放在星号之后:

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;

我个人采用 always 将 const 放在我不打算修改的部分之后,这样即使指针是我希望保持不变的部分,我也能保持一致性.

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.

相关文章