“第一次尝试”没有编译,而第二次尝试编译了。为什么?有什么关系呢?
第一次尝试:
#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 发布于 2015-11-13 20:40:04
从草案C++11标准部分5.19 expr.const中,我们可以看到address constant expression是(强调我的前进):
...指针类型的prvalue核心常量表达式,其计算结果为具有静态存储持续时间的对象的地址、函数的地址、空指针值或std::nullptr_t类型的prvalue核心常量表达式。
在第一种情况下,虽然"hello"是一个字符串文字,但它具有静态存储持续时间。它被复制到没有静态存储持续时间的数组text2中。
而在第二种情况下,text1是指向具有静态存储持续时间的string literal的指针。
更改您的第一个示例,使text2成为静态():
constexpr char static text2[] = "hello";
^^^^^^我们不再收到错误。
我们可以从2.14.5 lex.string一节中看到一个具有静态存储持续时间的字符串
普通字符串文字和UTF8字符串文字也称为窄字符串文字。窄字符串文字的类型为“array const char”,其中n是如下定义的字符串大小,并具有静态存储持续时间(3.7)。
https://stackoverflow.com/questions/33692872
复制相似问题