In C++20, what does constinit guarantee for a global or thread_local variable, and how does it differ from constexpr?
answer
- initialized, not frozen
- static initialization or a build error
- not usable in constant expressions
- no per-access guard for thread_local
basics
~20 sconstinit (C++20) requires a variable with static or thread storage duration to be initialized at compile time, or the program is ill-formed, but leaves it mutable. constexpr also requires a constant initializer, makes the variable const and usable in constant expressions.
solid answer
~40 s`constinit` asserts that a variable with static or thread storage duration gets **constant initialization**: its initializer must be a constant expression, or the declaration is a compile error, `variable does not have a constant initializer` in Clang. Unlike `constexpr`, it does not make the variable `const`: `constinit std::uint32_t g_next_seq = seed();` can be incremented at run time. It is also not usable in constant expressions, so `static_assert(g_next_seq == ...)` fails. It cannot be applied to a local automatic variable. What it buys is that no dynamic initialization happens, so the variable has its value before any code runs, which removes its part in initialization-order problems between translation units. For a `thread_local`, compilers following the Itanium C++ ABI can then also skip the wrapper call that checks for dynamic initialization on access.
code
cpp · 18 lines#include <cstdint>
#include <cstdio>
constexpr std::uint32_t seed() { return 0x1234u; }
std::uint32_t seed_from_config() { return 0x5678u; } // not constexpr
constinit std::uint32_t g_next_seq = seed(); // static initialization, still mutable
constinit thread_local std::uint32_t t_packets = 0; // per-thread, no dynamic init
constexpr std::uint32_t kMagic = seed(); // const, usable in constant expressions
// constinit std::uint32_t g_bad = seed_from_config(); // error: needs a constant initializer
int main() {
++g_next_seq; // fine: constinit does not imply const
++t_packets;
// ++kMagic; // error: constexpr variables are const
// static_assert(g_next_seq == 0x1234u); // error: not usable in constant expressions
std::printf("%X %u %X\n", g_next_seq, t_packets, kMagic);
}go deeper
Recall that constinit checks that a global or thread_local is initialized at compile time and leaves it modifiable.
Contrast constinit with constexpr: const or not, usable in constant expressions or not, and which variables each may apply to.
Use constinit on mutable globals and thread_locals to remove them from initialization-order problems and to catch a refactor that makes their initializer dynamic.
Make constinit the required form for mutable globals in shared libraries, so a variable's initialization mode is checked rather than assumed.
## Constant initialization, stated as a requirement A variable with **static storage duration** (a global, a namespace-scope variable, a static data member, a function-local `static`) or **thread storage duration** (`thread_local`) is initialized in one of two ways: - **Constant initialization**: the initializer is a constant expression, so the value is computed by the compiler and the variable simply starts with it. No code runs. - **Dynamic initialization**: the initializer runs as code, at startup for globals or on first use for function-local statics and many `thread_local`s. Which one a variable gets has always depended on its initializer, silently. A change to a function called in the initializer, such as removing `constexpr` from it, could switch a global from constant to dynamic initialization without any diagnostic. `constinit` (C++20) turns the expectation into a check. The draft states that if a `constinit` variable has dynamic initialization, the program is ill-formed. ## constinit versus constexpr | | `constexpr` variable | `constinit` variable | |---|---|---| | Initializer must be a constant expression | yes | yes | | Variable is `const` | yes, implicitly | no, it can be modified | | Usable in constant expressions | yes | no | | Allowed on local automatic variables | yes | no: static or thread storage only | | Can be declared `extern` without its initializer | no: every declaration needs the initializer | yes, and the initializing declaration must carry `constinit` | So `constexpr` is for **values**, compile-time constants, and `constinit` is for **variables** that must start with a compile-time value but change afterwards: counters, sequence numbers, caches, state tables. ## A network stack's mutable globals ```cpp constinit std::uint32_t g_next_seq = seed(); // static init, still mutable constinit thread_local std::uint32_t t_packets = 0; // per-thread counter constinit std::uint32_t g_bad = seed_from_config(); // error ``` `seed()` is `constexpr`, so the first line compiles and `++g_next_seq` works later. `seed_from_config()` is an ordinary function, so Apple clang 21 rejects the third line with `variable does not have a constant initializer` and the note `required by 'constinit' specifier here`. Trying `static_assert(g_next_seq == 0x1234u)` fails with `read of non-const variable 'g_next_seq' is not allowed in a constant expression`, which is the second difference from `constexpr`. And `constinit int x = 0;` inside a function body is rejected: `local variable cannot be declared 'constinit'`. ## Why it matters in practice 1. **Initialization order.** Dynamic initialization of globals in different translation units happens in an unspecified order relative to each other; a global read by another global's dynamic initializer may not be initialized yet. A `constinit` variable is never in that race, because it has no dynamic initialization. The general rules of storage duration and initialization order are covered with object lifetime; `constinit` is how you **prove** a given variable is out of it. 2. **Refactoring safety.** If someone later makes `seed()` non-`constexpr`, the build breaks at the `constinit` declaration instead of the variable quietly becoming dynamically initialized. 3. **`thread_local` access cost.** When a `thread_local` defined in another translation unit might need dynamic initialization, compilers following the Itanium C++ ABI route each access through a wrapper function. With `extern constinit thread_local int t;` the compiler knows no initialization is needed. Compiling `int get() { return t; }` with Apple clang 21 at `-O2` showed a call to the wrapper `_ZTW1t` without `constinit` and a direct thread-local access with it. That is one ABI's mechanism, not something the standard specifies. ## Combining with const `constinit const int x = 42;` is legal and behaves almost like `constexpr int x = 42;`, but the two cannot be stacked: the draft allows at most one of `constexpr`, `consteval` and `constinit` in a declaration, and Clang rejects `constinit constexpr` with `cannot combine with previous 'constinit' declaration specifier`. If a value never changes, write `constexpr`. If it changes, write `constinit`. ## What to say `constinit` guarantees compile-time initialization and nothing else: the variable stays mutable, is not usable in constant expressions, and applies only to static and thread storage. It is the checked form of what `constexpr` gives a constant, applied to variables that must start initialized but are allowed to change.
- Can a constinit variable be declared extern in a header and defined in one .cpp file?Yes. The draft requires `constinit` on the initializing declaration, the definition in the .cpp file. Other declarations may carry it too, and repeating it on the header's `extern` declaration is what lets the compiler skip initialization checks at uses. No diagnostic is required if no `constinit` declaration is reachable at the initializing declaration, so keep the header and the definition consistent.
- Why is a constinit variable not usable in constant expressions even though its initial value is known?Because it is not `const`: code can modify it at run time, so its value at any later point is not a compile-time fact. A variable is usable in constant expressions only if it is `constexpr` or a constant-initialized `const` integral, enumeration or reference variable. Declaring it `constinit const` would satisfy that for an integral type, at which point `constexpr` says it more directly.
A stage set must be fully built before the doors open, yet actors may still move the furniture during the play; a constexpr value is the painted backdrop, finished in advance and never touched.
- constinit makes the variable const, like constexpr.
- A constinit global can be used as a template argument.
- constinit can mark any local variable to force compile-time init.
- constinit falls back to dynamic initialization when the initializer is not constant.
- constinit makes every global in the same file statically initialized.
Assumes C++20, which added the constinit specifier; earlier standards can only hope a variable gets constant initialization.