c++ 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
是(重點是煤鑼前進):
[…] a prvalue core constant expression
pointer type that evaluates to the address of an object with
, to the address of a function, or to a nullpointer value, or a prvalue core constant expression of type
std::nullptr_t.
在第一種情況下,雖然“hello”是一個具有靜態儲存持續時間的字串文字.它被複制到沒有靜態儲存持續時間的陣列text2中.
而在第二種情況下,text1是指向具有靜態儲存持續時間的string literal 的指標.
改變你的第一個例子,使text2 static(see it live ):
constexpr char static text2[] = "hello"; ^^^^^^
我們不再收到錯誤.
我們可以看到一個字串文字具有從2.14.5節[lex.string]的靜態儲存時間:
Ordinary string literals and UTF-8 string literals are also referredto as narrow string literals. A narrow string literal has type “arrayof n const char”, where n is the size of the string as defined below,and has static storage duration (3.7).
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/33692872/constexpr-const-char-vs-constexpr-const-char