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

时间:2011-11-11 09:10:02

标签: c++ pointers const

根据我的理解,const修饰符应该从右到左阅读。从那以后,我明白了:

const char*

是一个指针,其char元素不能被修改,但指针本身可以和

char const*

是指向mutable字符的常量指针。

但是我对以下代码有以下错误:

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)错了?

6 个答案:

答案 0 :(得分:127)

实际上,根据标准,const会将元素直接修改为其左侧。在声明开头使用const只是一种方便的心理捷径。所以以下两个陈述是等价的:

char const * pointerToConstantContent1;
const char * pointerToConstantContent2;

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

char * const constantPointerToMutableContent;

要保护指针及其指向的内容,请使用两个consts。

char const * const constantPointerToConstantContent;

我个人采用总是将const放在我打算不修改的部分之后,即使指针是我希望保持不变的部分,我仍保持一致性。

答案 1 :(得分:29)

它的作用是因为两者都相同。你可能会对此感到困惑,

const char*  // both are same
char const*

char* const  // unmutable pointer to "char"

const char* const  // unmutable pointer to "const char"

[要记住这一点,这是一个简单的规则,'*'首先影响整个LHS ]

答案 2 :(得分:24)

那是因为规则是:

RULE:const左边绑定,除非左边没有任何东西,然后它绑定右边:)

所以,看看这些:

(const --->> char)*
(char <<--- const)*
两个都一样!哦,--->><<---不是运算符,它们只显示const绑定的内容。

答案 3 :(得分:11)

(来自2 simple variable initialization question

关于const的一个非常好的经验法则:

  

从右到左阅读声明。

(参见Vandevoorde / Josutiss“C ++模板:完整指南”)

例如:

int const x; // x is a constant int
const int x; // x is an int which is const

// easy. the rule becomes really useful in the following:
int const * const p; // p is const-pointer to const-int
int const &p;        // p is a reference to const-int
int * const * p;     // p is a pointer to const-pointer to int.

自从我遵循这个经验法则后,我再也没有误解过这样的声明。

(:sisab retcarahc-rep a no ton,sisab nekot-rep a tfel-ot-thgir naem I hguohT:tidE

答案 4 :(得分:5)

以下是我总是试图解释:

char *p

     |_____ start from the asterisk. The above declaration is read as: "content of `p` is a `char`".

char * const p

     |_____ again start from the asterisk. "content of constant (since we have the `const` 
            modifier in the front) `p` is a `char`".

char const *p

           |_____ again start from the asterisk. "content of `p` is a constant `char`".

希望它有所帮助!

答案 5 :(得分:0)

在您的两种情况下,您都指向一个常量字符。

Your current session has lasted 00:00:07.00.

默认情况下,const char * x //(1) a variable pointer to a constant char char const * x //(2) a variable pointer to a constant char char * const x //(3) a constant pointer to a variable char char const * const x //(4) a constant pointer to a constant char char const * const * x //(5) a variable pointer to a constant pointer to a constant char char const * const * const x //(6) can you guess this one? 适用于剩下的内容,但如果在其之前没有任何内容,它可以适用于其右边的内容,如(1)中所述。

相关问题