最佳答案
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 constinit
mean? Why was it introduced? In which cases should we use it?
Does it make a variable immutable? Does it imply const
or constexpr
?
Can a variable be both const
and constinit
? What about constexpr
and constinit
?
To which variables can the specifier be applied? Why cannot we apply it to non-static
, non-thread_local
variables?
Does it have any performance advantages?
This question is intended to be used as a reference for upcoming questions about constinit
in general.