可以将C-Strings或std::string
创建为constexpr
还是必须在运行时创建?为什么必须在运行时构建一个字符串?
用gcc 4.9.2我可以这样做:
constexpr const char foo[] = "blee";
(可悲的是2013年11月客户技术预览不允许Visual Studio来支持这一点:https://stackoverflow.com/a/29255013/2642059)
但即便用gcc 4.9。 2我不能做到这一点:
constexpr const std::string foo = "blee";
我得到的错误:
error: the type 'const string {aka const std::basic_string<char>}' of constexpr variable 'foo'
is not literal
constexpr const std::string foo = "blee";
^
note: 'std::basic_string<char>' is not literal because:
class basic_string
^
note: 'std::basic_string<char>' has a non-trivial destructor
但我想对进行更多的说明,为什么 a std::string
不是文字。也就是说:为什么必须在运行时构建一个字符串?
正如指出的这个问题可以部分回答这个:Is it possible to use std::string in a constexpr?但它并没有涉及为什么std::string
不能成为问题的核心文字。
对此问题感兴趣的人被[这个问题]的回答激怒了(http://stackoverflow.com/q/29166578/2642059)。 – 2015-03-25 12:13:46
@juhist啊,我不知道我在搜索时错过了什么。所以答案是'std :: string'不是一个文字?为什么会这样?看起来像将const std :: string一个文字一样简单。 – 2015-03-25 12:17:13
我想在其他答案中给出原因:因为'std :: basic_string'有一个不平凡的析构函数。 – juhist 2015-03-25 12:19:20