2

According to this question and other sources, most constructors for std::string are constexpr as of C++20.

Below, I attempt to use constructor (5) from here:

#include <iostream>
#include <string>

int main() {
    constexpr std::string example{ "word" };
    std::cout << example;
}

I ran this in Microsoft Visual Studio Community 2019 Version 16.11.4 with both /std:c++20 and /std:c++lastest enabled.

Both give the error

error C2131: expression did not evaluate to a constant
message : failure was caused by allocated storage not being deallocated

According to row "constexpr std::string" in this table, the feature should be present.

Am I doing something wrong? Has this feature been implemented?

user589321
  • 99
  • 6
  • 5
    Unfortunately the most-upvoted answers on that question were written years before C++20 was actually finalized, and it turns out that the utility of `std::string`'s `constexpr` constructors is somewhat narrower than predicted. [This answer](https://stackoverflow.com/a/69590837/12334309) has more details about the circumstances in which you can and cannot make use of the `constexpr` constructors. – Nathan Pierson Mar 02 '22 at 23:23
  • Thanks! I'll add for future readers that this also applies to ```constexpr std::vector```. – user589321 Mar 02 '22 at 23:32
  • Yes, anything that has to make heap allocations can only do so transiently. – Nathan Pierson Mar 02 '22 at 23:33

0 Answers0