What is constinit Specifier?

The constinit specifier is used to mark variables that must be initialized with compile-time constant expressions or constant-initialized constructors and it also ensures that the initialization will be done during the static initialization phase. It prevents the variables with static storage duration to be initialized at runtime. The variables specified with constinit specifier need to be initialized with a constant expression.

Note: constinit cannot be used together with constexpr or consteval as constinit is used for static initialization of variables, which happens before the program starts the execution, whereas constexpr and consteval are used to evaluate the expression at compile time.

Syntax

constinit T variable = initializer;

Where,

  • T: It indicates the type of variable
  • variable: It is the name of the variable
  • initializer: It is the constant expression that is used for the initialization.

constinit Specifier in C++ 20

The constinit specifier is a new feature that is introduced in C++ 20 that allows us to declare a variable with static storage duration. In this article we will discuss the constinit specifier, its usage, advantages, and limitations.

Similar Reads

What is constinit Specifier?

The constinit specifier is used to mark variables that must be initialized with compile-time constant expressions or constant-initialized constructors and it also ensures that the initialization will be done during the static initialization phase. It prevents the variables with static storage duration to be initialized at runtime. The variables specified with constinit specifier need to be initialized with a constant expression....

Examples of constinit

Example 1:...

Advantages of constinit

...