可以在运行时创建C-Strings还是std::string必须创建constexpr它们?
使用gcc 4.9.2我可以这样做:
constexpr const char foo[] = "blee";
Run Code Online (Sandbox Code Playgroud)
(遗憾的是,2013年11月的客户技术预览版不允许Visual Studio支持此功能:https://stackoverflow.com/a/29255013/2642059)
但即使使用gcc 4.9.2我也不能这样做:
constexpr const std::string foo = "blee";
Run Code Online (Sandbox Code Playgroud)
我收到错误:
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
Run Code Online (Sandbox Code Playgroud)
但我想更多地澄清为什么 a std::string不是文字.也就是说:为什么必须在运行时构造字符串?
正如所指出的,这个问题可以部分回答:是否可以在constexpr中使用std :: string?但它没有涉及为什么std::string不能成为问题核心的文字.