Aussie AI
constinit variables
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
constinit variables
The constinit specifier is like a hybrid between consteval and static variables.
The constinit specifier declares a variable that is static,
with lifetime scope,
that is initialized at compile-time.
A variable declared as constinit must be initialized, and cannot be modified (like “const”).
However, the initializer needn't be a “constant expression” although it
must be able to be calculated at compile-time.
Huh? That makes no sense. Sure, it does in the world of C++ standards. A “constant expression” with only constant arithmetic is a subset of the set of expressions that can be calculated at compile-time.
The best example is a call to a function that has one path where it's constant,
and another path where it's not.
The definition of “somefunc” has two paths:
int somefunc()
{
if (something) return 27;
else return some_random_number();
}
The “somefunc” function cannot be declared “const” or “constexpr” because it isn't always a constant
on all paths.
However, if we're using “somefunc” at program startup initialization, we can try:
constinit int s_myconst = somefunc();
Here, if we know that it will use the constant path for some reason,
the initialization of “s_myconst” will go through the fixed path to get
the compile-time constant value of 27, we can tell the compiler that by declaring the variable as constinit.
Anyway, now that you've been forced to learn all that, just forget it. You'll rarely if ever be needing constinit.
|
• Next: • Up: Table of Contents |
|
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |