下面的代碼編譯:
#include <iostream>
int main( )
{
const char* const str = "This is a constant string.";
std::cout << str << '\n';
}
然而,這個給出了一個警告:
constexpr char* const str = "This is a constant string.";
這里:
warning: ISO C forbids converting a string constant to 'char*' [-Wwrite-strings]
37 | constexpr char* const str = "This is a constant string.";
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
這是 GCC 中的錯誤嗎?我正在將字串轉換為指向constexpr char陣列的指標。這個警告有效嗎?
現在制作指標本身constexpr可以防止它被編譯:
const char* constexpr str = "This is a constant string.";
這里:
error: expected unqualified-id before 'constexpr'
37 | const char* constexpr str = "This is a constant string.";
| ^~~~~~~~~
為什么指標不能是 constexpr?
uj5u.com熱心網友回復:
您是否在這里使用 constexpr 不是問題。您正在嘗試將字串文字存盤在 char* const 中,它不是指向不可變資料(字串文字是)的指標,而是具有常量地址的指標。字串文字可以存盤為 const char* 或 const char* const 代替。
const char* str = "This is a constant string."
添加 constexpr 看起來像這樣:
constexpr const char* str = "This is a constant string."
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/402514.html
標籤:
