Function returning constexpr does not compile [duplicate]
Asked Answered
N

1

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");
}
Nea answered 15/10, 2011 at 16:15 Comment(0)
L
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.

Lib answered 15/10, 2011 at 16:22 Comment(9)
Thanks, didn't know that before.Nea
+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.Obie
But don't you think that this is (this particular example) bit silly? the string literal is const, so I think ctor of string should be made constexpr as to allow such constructs in the future.Nea
@JonPurdy ctor CAN be constexprNea
@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.Obie
@JonPurdy I just said that a ctor CAN BE constexpr.Nea
@smallB: Okay. I never said anything to the contrary.Obie
@Nea 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.Pitarys
@JonPurdy fair enough, that was just misunderstanding.Nea

© 2022 - 2024 — McMap. All rights reserved.