88

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.

Acorn
  • 24,970
  • 5
  • 40
  • 69

2 Answers2

94
  • What does constinit mean? Why was it introduced? In which cases should we use it?

Initializing a variable with static storage duration might result in two outcomes¹:

  1. The variable is initialized at compile-time (constant-initialization);

  2. 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 constinit keyword 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 constinit ensures that the variable is initialized at compile-time, and that the static initialization order fiasco cannot take place.


  • Does it make a variable immutable? Does it imply const or constexpr?

No and no.

However, constexpr does imply constinit.


  • Can a variable be both const and constinit? What about constexpr and constinit?

It can be both const and constinit. It cannot be both constexpr and constinit. From the wording:

At most one of the constexpr, consteval, and constinit keywords shall appear in a decl-specifier-seq.

constexpr is not equivalent to const constinit, as the former mandates constant destruction, while the latter doesn't.


  • To which variables can the specifier be applied? Why cannot we apply it to non-static, non-thread_local variables?

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 constinit is all about static initialization.


  • Does it have any performance advantages?

No. However, a collateral benefit of initializing a variable at compile-time is that it doesn't take instructions to initialize during program execution. constinit helps 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

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • 2
    *"cannot be both `constexpr` and `constinit`"* Is that because `constexpr` effectively implies `constinit`? – HolyBlackCat Sep 08 '19 at 19:47
  • 4
    "`constexpr` does imply `constinit`" - I'd not say so, since `constexpr` might be applied to local variables, while `constinit` cannot. – Mikhail Oct 19 '19 at 16:34
  • "It can be both const and constinit". Is that effectively the same as constexpr? Also can you clarify why it does not make sense to apply constinit to local variables? – pooya13 Nov 25 '19 at 21:13
  • @pooya13: 1. no, `constexpr` also mandates constant destruction. 2. it doesn't make sense because non-`static` local variables can't be initialized at compile-time. – Vittorio Romeo Nov 26 '19 at 09:25
  • @Mikhail: But it is fair to say that it implies `constinit` for a non-local variable (and always implies `const` and a bit more). – Davis Herring Nov 27 '19 at 01:56
  • It doesn’t make sense to talk about *all* dynamic initialization as happening when “control passes through its declaration”; that’s only for local statics. – Davis Herring Nov 27 '19 at 02:00
  • 2
    "constexpr mandates *constant destruction*". Can you just hint what does this means? – mada Dec 12 '21 at 14:05
  • 1
    @meda, probably that the type needs a `constexpr` destructor. (Before C++20, the destructor had to be trivial, i.e. `= default`.) – Quirin F. Schroll Sep 14 '22 at 12:51
4

MAIN PROBLEM:

An object is considered to be initialized only when the control passes through its declaration or its definition; otherwise (i.e the control jump into a function defined in the source file in which this object is declared or defined, it doesn't see it at all) any access to this uninitialized object is undefined behavior.

Moreover, the order of initializing static-duration objects defined into multiple translation units is also undefined. You don't have a way in code to request the compiler to initialize a static object before or after another one because one object is depending on the other. Actually you cannot do this. It's up to the compiler to decide which object should be initialized first; in particular this actually depends on the order of compiling each source file.

Example - Segmentation fault

// main.cpp
#include "src1.h"
A a{ 10 };      // declaring an object of class A with static duration.
int main() {}

// src1.cpp
#include "src1.h"
#include "src2.h"
B b{ 20 };      // declaring an object of class B with static duration.
A::A(int x): m_x(x) { b.f(); }

//src2.cpp
#include "src2.h"
int B::f() { return m_x; }
B::B(int x):  m_x(x) { }

//src1.h
struct A { 
    private: int m_x;
    public: A(int); 
};

//src2.h
struct B { 
    private: int m_x;
    public: B(int); int f(); 
};

g++ main.cpp src1.cpp src2.cpp // OK: main.cpp should be compiled first
g++ main.cpp src2.cpp src1.cpp // OK: main.cpp should be compiled first
g++ any_other_order // sigfault

WORKAROUND:

constinit gets introduced in C++20

xryl669
  • 3,376
  • 24
  • 47
mada
  • 1,646
  • 1
  • 15
  • It actually depends on the order the object files are linked. See [Static variables initialisation order](https://stackoverflow.com/q/211237/12447766). – Burak May 26 '22 at 04:44
  • 2
    Could you explain *why* main.cpp must be compiled first? It makes no sense to me. – Quirin F. Schroll Sep 14 '22 at 12:36