11

Why doesn't this compile:
Could there be a problem with a string as a return type?

constexpr std::string fnc()
{
    return std::string("Yaba");
}
0

1 Answer 1

14

The constructor of std::string that takes a pointer to char is not constexpr. In constexpr functions you can only use functions that are constexpr.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks, didn't know that before.
+1 and the reason that that constructor can’t be constexpr is that it has side-effects (namely allocation) that can’t be carried out at compile time.
@smallB: A constant-expression constructor must be 1. declared constexpr 2. have a member-initializer part involving only potential constant-expressions and 3. have an empty body. It seems to me that std::string has to violate #2.
@smallB: Okay. I never said anything to the contrary.
@smallB You can't have a constexpr constructor for std::string that takes arbitrary length const char* and be safe. While it's true that string literals are constant expressions, there are plenty of things of type const char* that are not constant expressions. The c_str member of std::string comes to mind. Overloading on constexpr is not available to distinguish between the two.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.