constexpr const char * 与 constexpr const char[]

constexpr const char * vs constexpr const char[]

"first attempt" 无法编译,而第二个可以。为什么?有什么区别?

第一次尝试:

#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] 我们可以看到 address constant expression 是 (强调矿工前进):

[...] a prvalue core constant expression of pointer type that evaluates to the address of an object with static storage duration, to the address of a function, or to a null pointer value, or a prvalue core constant expression of type std::nullptr_t.

在您的第一种情况下,尽管 "hello" 是一个具有静态存储持续时间的字符串文字。它被复制到一个没有静态存储持续时间的数组 text2 中。

虽然在你的第二种情况下 text1 是指向具有静态存储持续时间的 string literal 的指针。

更改您的第一个示例,使 text2 静态化 (see it live):

constexpr char static text2[] = "hello";
               ^^^^^^

我们不再收到错误。

我们可以从 2.14.5 [lex.string]:

部分看到字符串文字具有静态存储持续时间

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).