constinit is a new keyword and specifier in C++20 which was proposed in P1143.
The following example is provided in the standard:
const char * g() { return "dynamic initialization"; }
constexpr const char * f(bool p) { return p ? "constant initializer" : g(); }
constinit const char * c = f(true); // OK
constinit const char * d = f(false); // ill-formed
A few questions come to mind:
What does
constinitmean? Why was it introduced? In which cases should we use it?Does it make a variable immutable? Does it imply
constorconstexpr?Can a variable be both
constandconstinit? What aboutconstexprandconstinit?To which variables can the specifier be applied? Why cannot we apply it to non-
static, non-thread_localvariables?Does it have any performance advantages?
This question is intended to be used as a reference for upcoming questions about constinit in general.
Initializing a variable with static storage duration might result in two outcomes¹:
The variable is initialized at compile-time (constant-initialization);
The variable is initialized the first time control passes through its declaration.
Case (2) is problematic because it can lead to the static initialization order fiasco, which is a source of dangerous bugs related to global objects.
The
constinitkeyword can only be applied on variables with static storage duration. If the decorated variable is not initialized at compile-time, the program is ill-formed (i.e. does not compile).Using
constinitensures that the variable is initialized at compile-time, and that the static initialization order fiasco cannot take place.No and no.
However,
constexprdoes implyconstinit.It can be both
constandconstinit. It cannot be bothconstexprandconstinit. From the wording:constexpris not equivalent toconst constinit, as the former mandates constant destruction, while the latter doesn't.It can only be applied to variables with static or thread storage duration. It does not make sense to apply it to other variables, as
constinitis all about static initialization.No. However, a collateral benefit of initializing a variable at compile-time is that it doesn't take instructions to initialize during program execution.
constinithelps developers ensure that is the case without having to guess or check the generated assembly.¹: See https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables