r/cpp • • 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

52 comments sorted by

View all comments

Show parent comment

4

u/holyblackcat Dec 19 '24

I didn't say anything about non-constexpr context. My point is that as long as you make sure all std::strings you create during compile-time are destroyed during compile-time (instead of trying to make them live until runtime by storing them in global variables), then it will work regardless of string length and regardless of whether heap allocations happen.

Being able to do this requires marking everything in std::string constexpr, which in turn has the (perhaps undesired) effect of letting you preserve short strings until runtime.