2

C++20 added constexpr std::strings (among many other constructs that have until then not been constexpr-able). According to the compiler compliance list at https://en.cppreference.com/w/cpp/compiler_support#cpp20, the three big compilers now support constexpr std::string operations. However, my simple attempts to exercise constexpr strings have failed (https://compiler-explorer.com/z/c1can1P6Y). Consider the following:

#include <string>

constexpr std::string s = "abc"; // Global variable, supported by only GCC

int main()
{
  constexpr std::string t = "def"; // Not supported by GCC 12, Clang 15, or MSVC 19.33
}

I would have expected both s and t to be constexpr-constructible. But the fact that cppreference.com states all three compilers support constexpr strings and yet Compiler explorer largely rejects my simple test above make me wonder if my expectations need to be adjusted.

The Question: With C++20, should I be able to constexpr-construct both s and t above?

KyleKnoepfel
  • 1,426
  • 8
  • 24
  • 1
    There is a dupe for this but TL;DR is that you are only allowed to declare a constexpr string in a constexpr function. You can't have just a plain constexpr std::string. – NathanOliver Nov 14 '22 at 21:46
  • Neither is specified to work. However it is also not specified that either must result in a diagnostic. See duplicates for what `constexpr std::string` support really means. (It doesn't mean that a `std::string` can be `constexpr`.) – user17732522 Nov 14 '22 at 21:47
  • Ah, thanks @NathanOliver. This seems to suggest that the keyword `constexpr` is not intended to be used with std::string...even though `constexpr` operations are supported. – KyleKnoepfel Nov 14 '22 at 21:51
  • 1
    @KyleKnoepfel That is correct. `std::string` allocates memory and you can't do that at compile time. That means you can only create the string if you don't keep it past the context where it is used like in the example of the dupe of `constexpr int f() { std::string s = "something"; return s.size(); }`. Without constexpr support that function couldn't be called at compile time. – NathanOliver Nov 14 '22 at 21:55

0 Answers0