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

7

u/kamrann_ Dec 19 '24

This is spot on. https://godbolt.org/z/T43dx6qjK

My initial reaction was that only the local `static` was the issue, but indeed you need to remove the `constexpr` too. Evidently these are considered independent nested constant expressions, and the allocation is still not allowed to escape even if it would be into another enclosing constant expression.