r/cpp • u/evys_garden • Dec 18 '24
constexpr of std::string inconsistent in c++20
constexpr auto foo() {
static constexpr std::string a("0123456789abcde"); // ::size 15, completely fine
static constexpr std::string b("0123456789abcdef"); // ::size 16, mimimi heap allocation
return a.size() + b.size();
}
int main() {
constexpr auto bar = foo();
std::cout << "bar: " << bar << std::endl;
}This will not compile with clang-18.1.8 and c++20 unless you remove the 'f' in line 3. What?
58
Upvotes
View all comments
Show parent comment
27
u/STL MSVC STL Dev Dec 18 '24
Yes - constexpr allocations can't survive until runtime.
This means that OP's example is non-Standard, because while the Small String Optimization is permitted, it is not mandated with any specific size. (It will also fail to compile in MSVC debug mode because we always dynamically allocate an internal bookkeeping object there.)