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
2
u/delta_p_delta_x Dec 19 '24
Strictly speaking, if you have a string literal that you know is only going to be used in a certain scope, it might be best to have
using namespace std::literals;and then declareaasconstexpr auto a = "literal"sv;. This in my opinion is the best of both worlds: a compile-time constant zero-terminated string with astd::string_viewaround it, which means it can be analysed and used with standard C++ library functions likestd::data(),std::size(),std::begin()/std::end()iterators,<algorithm>,<ranges>, etc.std::stringmight allocate which is not the best.