The constinit Keyword

Understand the use of the 'constinit' keyword in C++20.

We'll cover the following

Introduction

constinit can be applied to variables with static storage duration or thread storage duration:

  • Global (namespace) variables, static variables, or static class members have static storage duration. These objects are allocated when the program starts and are deallocated when the program ends.
  • thread_local variables have thread storage duration. Thread-local data is created for each thread that uses this data. thread_local data exclusively belongs to the thread. They are created at its first usage and its lifetime is bound to the lifetime of the thread it belongs to. Often thread-local data is called thread-local storage.

Example

constinit ensures for this kind of variable (static storage duration or thread storage duration) that they are initialized at compile time. constinit does not imply constnessThe declaration of variables or objects as immutable.

Get hands-on with 1400+ tech skills courses.