constexpr const char * vs constexpr const char[]
constexpr const char * vs constexpr const char[]
"第一次尝试"不编译,而第二次尝试编译。为什么?有什么区别?
第一次尝试:
#include <iostream>
int main()
{
constexpr const char text2[] = "hello";
constexpr const char * b = &text2[4]; // error: '& text2[4]' is not a constant expression
std::cout << b << std::endl;
}
第二次尝试:
#include <iostream>
int main()
{
constexpr const char * text1 = "hello";
constexpr const char * a = &text1[4];
std::cout << a << std::endl;
return 0;
}
我使用(g++版本4.9.2)进行编译
g++ -std=c++11 -o main *.cpp
其给出以下错误
main.cpp: In function 'int main()':
main.cpp:7:40: error: '& text2[4]' is not a constant expression constexpr const char * b = &text2[4]; // error: '& text2[4]' is not a constant expression
从C++11标准草案5.19
[expr.const]中,我们可以看到一个地址常量表达式是(emphasis mine gong forward):
[…]一个prvalue核心常量表达式的指针类型,计算结果为具有静态存储持续时间、函数地址或null指针值,或类型为的prvalue核心常量表达式std::nullptr_t。
在第一种情况下,尽管"hello"
是一个具有静态存储持续时间的字符串文字。它被复制到没有静态存储持续时间的阵列text2
中。
而在第二种情况下,text1
是指向具有静态存储持续时间的字符串文字的指针。
更改您的第一个示例以使text2
静态(实时查看):
constexpr char static text2[] = "hello";
^^^^^^
我们不再有错误。
我们可以从2.14.5
[lex.string]:部分看到字符串文本具有静态存储持续时间
还引用了普通字符串文字和UTF-8字符串文字到作为窄字符串文字。窄字符串文字的类型为"array"of n const char",其中n是如下定义的字符串的大小,并且具有静态存储持续时间(3.7)
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 在 constexpr 构造函数 (c++17) 中赋值到 const char * 在使用 Android NDK 时
- 带有 char[] 字段的 POD 结构的 constexpr 构造
- 为什么这两段使用 constexpr、__PRETTY_FUNCTION__ 和 char * 的代码有不同的结果?
- 有什么陷阱用 constexpr string_view 替换全局 const char[]?
- 无法声明静态 constexpr char []
- 将 'hana::string' 转换为 'constexpr const char (&)[]'
- 通过 constexpr 中的 'const char *' glvalue 访问字符串文字的值会出错
- 列出<Char>C++中键入的 constexpr 字符串
- constexpr static std::array<const char *,5> 无法使用 MSVC2013 进行编译
- 预处理器检查 constexpr const char* 函数
- 警告:ISO C++禁止将静态“constexpr char*”数据成员的字符串常量转换为“char*”
- 链接器错误(未定义的引用)与“静态 constexpr const char*”和完美转发
- 使用 const char 数组参数分析 constexpr 显示运行时执行
- static_assert 无法将 const char* 模板参数识别为 constexpr:g++ 错误?
- constexpr char[] 作为类成员有什么好处
- constexpr const char * vs constexpr const char[]
- 对静态constexpr char[]的未定义引用
- const constexpr char* vs. constexpr char*
- 字符串字面值与constexpr char数组的区别