const char *和char const * - 它们是否相同? [英] const char* and char const* - are they the same?

查看:478
本文介绍了const char *和char const * - 它们是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的理解, 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;

我已经亲自采用了不修改,即使指针是我希望保持不变的部分,我仍保持一致。

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.

这篇关于const char *和char const * - 它们是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆