Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

constinit

Use case

Ensure static variable is initialized at compile-time.

Explanation

constinit = compile-time init. Prevents static initialization order bugs.

Code

#include <cstdint>
#include <iostream>

constinit uint64_t g_baseAddr = 0x10000000;

int main() {
  std::cout << "Base: 0x" << std::hex << g_baseAddr << "\n";
  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/constinit
Base: 0x10000000