c++c++20constinit

Why can I define a std::string instance that is constinit? Isn't constinit forbidden if an object requires dynamic initialization?


The cppreference mentions that if initialization contains a dynamic initialization part, the program is ill-formed when using constinit in C++20.

I just wonder why the following code compiles then:

constinit std::string str = "Hello";

Since the std::string class involves dynamic memory allocation for storing characters, it seems contradictory. Shouldn't this be disallowed due to the dynamic part?

Tried to compile with flags -std=C++20 and the program compiles fine which shouldn't be.


Solution

  • Common std::string implementations don't allocate on the heap if the string is short enough (this is called the "short string optimization" or "SSO").

    Since the exact amount of characters that can fit into SSO (if any) depends on the implementation, you probably shouldn't rely on it, or should at least research how the big 3 standard libraries handle this.