Global variables are initialized before main()
runs, but the relative initialization order is not necessarily well-defined.
As such, accessing global state while you initialize your global variables, might not work the way you expect.
A simple solution is to stop using global variables completely.
However, it is not always an option, so in this talk we’ll discuss some real solutions to the problem.
We’ll cover simple wrappers, lazy initializers and nifty counters.
And of course, we’ll also discuss the best solution of them all - moving initialization to compile time with the help of constexpr
and C++20’s constinit
keywords.
See Also
- atum Library: github.com/foonathan/atum
- More C++ Idioms/Nifty Counter