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");
}
nbrooks
  • 18,126
  • 5
  • 54
  • 66
smallB
  • 16,662
  • 33
  • 107
  • 151

1 Answers1

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.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • Thanks, didn't know that before. – smallB Oct 15 '11 at 16:28
  • 2
    +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. – Jon Purdy Oct 15 '11 at 16:28
  • 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. – smallB Oct 15 '11 at 16:29
  • @JonPurdy ctor CAN be constexpr – smallB Oct 15 '11 at 16:30
  • 3
    @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. – Jon Purdy Oct 15 '11 at 16:34
  • @JonPurdy I just said that a ctor CAN BE constexpr. – smallB Oct 15 '11 at 16:36
  • 2
    @smallB: Okay. I never said anything to the contrary. – Jon Purdy Oct 15 '11 at 16:37
  • 1
    @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. – Luc Danton Oct 15 '11 at 16:50
  • @JonPurdy fair enough, that was just misunderstanding. – smallB Oct 15 '11 at 17:01