mercredi 25 mars 2015

Can a std::string be constexpr? [duplicate]


This question already has an answer here:




Can C-Strings or std::strings be created as constexpr or must they be created at run-time?


With gcc 4.9.2 I can do this:



constexpr const char foo[] = "blee";


(Sadly the November 2013 Customer Technology Preview does not allow Visual Studio to support this: http://ift.tt/19PeZWY)


But even with gcc 4.9.2 I cannot do this:



constexpr const std::string foo = "blee";


I get the error:



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


But I would like more clarification on why a std::string is not a literal. That is to say: Why must a string be constructed at run-time?


As pointed out this question can partially be answered by this: Is it possible to use std::string in a constexpr? but it do not touch on the why std::string can not be a literal which is core to the question.


Aucun commentaire:

Enregistrer un commentaire