Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

constinit — enforcing static initialization

constinit requires static initialization of a variable with static or thread storage duration. It does not make the variable immutable: it constrains initialization, not subsequent assignments.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

constinit T name = initializer;
static constinit T name = initializer;
thread_local constinit T name = initializer;

constinit requires a variable not to need dynamic initialization. Within the C++23 scope, it applies to variables with static or thread storage duration: for example, namespace-scope variables, local static variables, and thread_local variables. It does not apply to ordinary automatic local variables or functions.

Static initialization comprises constant initialization and zero-initialization and precedes dynamic initialization. If an initializer requires dynamic initialization, the program is ill-formed—even if the compiler could optimize it into static initialization. constinit is a language requirement, not an optimization hint.

Unlike constexpr applied to an object, constinit does not add const and does not by itself make the variable usable in constant expressions. Its value may subsequently change. You can combine constinit with const, but not with constexpr or consteval in the same declaration-specifier sequence.

If any declaration of a variable contains constinit, its initializing declaration must contain it too. If no declaration containing constinit is reachable at the initializing declaration, a violation requires no diagnostic. In the example, initial_value() supplies a constant initializer, while counter += 2 demonstrates a permitted later modification.

This entry targets C++23; a repository compiler flag does not attest production runtime compatibility. The source site publishes an evolving working draft, not a frozen C++23 text; later extensions are outside this entry's scope.

Examples

#include <iostream>

constexpr int initial_value() {
    return 40;
}

constinit int counter = initial_value();

int main() {
    counter += 2;
    std::cout << counter << '\n';
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources