HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

Is it possible to use std::string in a constant expression?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
constantpossibleusestdstringexpression

Problem

Using C++11, Ubuntu 14.04, GCC default toolchain.

This code fails:

constexpr std::string constString = "constString";



error: the type ‘const string {aka const std::basic_string}’ of
constexpr variable ‘constString’ is not literal... because...
‘std::basic_string’ has a non-trivial destructor

Is it possible to use std::string in aconstexpr? (apparently not...) If so, how? Is there an alternative way to use a character string in a constexpr?

Solution

No, and your compiler already gave you a comprehensive explanation.

But you could do this:

constexpr char constString[] = "constString";


At runtime, this can be used to construct a std::string when needed.

Code Snippets

constexpr char constString[] = "constString";

Context

Stack Overflow Q#27123306, score: 264

Revisions (0)

No revisions yet.