可以將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