字符串文字的 C++ const 正确性

标签 c++ constants

根据 C++ 标准,字符串字面量类型是 array of const char

auto constStr = "aaa";
char* nonConstStr = constStr; //Error here, cannot convert from 'const char *' to 'char *'
char* stillNonConstStr = "aaa"; //Why I don't have error here?

你能解释一下为什么在第 3 行我没有收到错误吗?

最佳答案

历史原因。即使字符串文字的类型是 const char 数组,过去也允许并且非常常见地将字符串文字分配给 char*。我相信它来自 C 不存在 const 的日子,但不要引用我的话。它后来被弃用,但仍然允许,以免破坏使用它的代码库。该允许不会扩展到允许 char*const char* (也不是从非文字的 const char 数组)初始化,这就是您的第二行失败的原因.在 C++11 中,禁止从字符串文字到 char* 的转换,但您的编译器可能还没有强制执行。

关于字符串文字的 C++ const 正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15355257/

相关文章:

c++ - int 数组中出现频率最低的公共(public)数

c++ - reinterpret_cast - 奇怪的行为

c++ - 在没有 'extern' 的情况下访问别处定义的变量值的最佳方法?

函数中的 C++ const 关键字

c# - 错误 C2664 - 需要帮助和说明

c++ - 我怎么知道什么时候用\n 输入完 cin? (环形)

c++ - 了解来自 tensorflow c++ API 的代码

c++ - 什么是左值?

c++ - 添加额外的 const 资格可以破坏功能(假设编译正常)?

c - 为什么 char *s = "string"在不是 const 时不显示错误或警告