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

const char* and char const* - are they the same?(const char* 和 char const* - 它们是一样的吗?)
本文介绍了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;

我个人采用 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.

这篇关于const char* 和 char const* - 它们是一样的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)