c++ - constexpr const 与 constexpr 变量?

标签 c++ c++11 constants constexpr

constexpr 隐含 const 似乎很明显,因此很常见:

constexpr int foo = 42; // no const here

但是如果你写:

constexpr char *const str = "foo";

如果传递了 -Wwrite-string 标志,GCC 将生成“警告:不推荐使用从字符串常量到‘char*’的转换”。

写作:

constexpr const char *const str = "foo";

解决问题。

那么 constexpr const 和 constexpr 真的是一样的吗?

最佳答案

问题是在变量声明中,constexpr 总是将 const 应用于声明的对象;另一方面,const 可以应用于不同的类型,具体取决于位置。

因此

constexpr const int i = 3;
constexpr int i = 3;

是等价的;

constexpr char* p = nullptr;
constexpr char* const p = nullptr;

是等价的;两者都使 p 成为指向 charconst 指针。

constexpr const char* p = nullptr;
constexpr const char* const p = nullptr;

是等价的。 constexpr 使 p 成为 const 指针。 const char * 中的const 使p 指向const char

关于c++ - constexpr const 与 constexpr 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31488757/

相关文章:

c++ - 好。将Leap带入C++。正确的决定?

c++ - C/C++ 程序的内存布局如何?

c# - 如何对 Windows API 常量进行分组

c++ - 在 const 成员函数中返回 C++ 引用

c++ - 从 GLSL 着色器获取常量

c++ - 用于 float 阈值操作的 SIMD

c++ - 具有默认值的结构的大括号(聚合)初始化

c++ - enable_if 使用 constexpr bool 测试不起作用

c++ - 标准布局 c++

c++ 使用包含 <time.h> 和 <ctime> 的 time() - 哪个优先?