为啥不能定义constexpr的string对象
为什么不能定义constexpr的string对象?
gcc下面:
编译不过,告诉我
error: the type 'const string {aka const std::basic_string<char>}' of constexpr variable 's' is not literal|
难道std的对象不能使用constexpr来定义和初始化为一个字面常量吗? 我不想用c风格数组,就想用std::string,能否做到?
谢谢。
------解决思路----------------------
编译时执行不了string的构造
用const std::string 或constexpr char s[]
------解决思路----------------------
既然都编译期确定不修改了, 直接用const char*. 连C风格的char[]都不要用.
既节约空间又高效, c/c++里面难得碰上这等好事都不用.
------解决思路----------------------
见lz的另外一篇我也回复了, 这样会导致每个源文件都有一份(相当于static), 造成内存的浪费.
对于编译期确定的, 用static const(expr) char* const, 编译器会优化的.
对于可能修改字符指针本身的, 用extern const char*, 再在某源文件初始化.
static不是c++专用的, 该用就用.
gcc下面:
int main()
{
constexpr string s="abc";
return 0;
}
编译不过,告诉我
error: the type 'const string {aka const std::basic_string<char>}' of constexpr variable 's' is not literal|
难道std的对象不能使用constexpr来定义和初始化为一个字面常量吗? 我不想用c风格数组,就想用std::string,能否做到?
谢谢。
------解决思路----------------------
编译时执行不了string的构造
用const std::string 或constexpr char s[]
------解决思路----------------------
既然都编译期确定不修改了, 直接用const char*. 连C风格的char[]都不要用.
既节约空间又高效, c/c++里面难得碰上这等好事都不用.
------解决思路----------------------
见lz的另外一篇我也回复了, 这样会导致每个源文件都有一份(相当于static), 造成内存的浪费.
对于编译期确定的, 用static const(expr) char* const, 编译器会优化的.
对于可能修改字符指针本身的, 用extern const char*, 再在某源文件初始化.
static不是c++专用的, 该用就用.