Solving the Static Initialization Order Fiasco
Get introduced to the static initialization order fiasco and learn how to solve it.
According to the FAQ at isocpp.org, the static initialization order fiasco is “a subtle way to crash your program”. The FAQ continues: “The static initialization order problem is a very subtle and commonly misunderstood aspect of C++.”
Before I continue, I want to make a short disclaimer. Dependencies on variables with static storage duration (short statics) in different
Static initialization order fiasco
Static variables in one translation unit are initialized according to their definition order.
In contrast, the initialization of static variables between translation units has a severe issue. When one static variable staticA
is defined in one translation unit and another static variable staticB
is defined in another translation unit, and staticB
needs staticA
to initialize itself, you end up with the static initialization order fiasco. The program is ill-formed because you have no guarantee which static variable is initialized first at (dynamic) run time.
Before I write about the solution, let me show you the static initialization order fiasco
in action.
A 50:50 chance to get it right
What is unique about the initialization of statics? The initialization-order of statics happens in two steps: static and dynamic.
When a static variable cannot be const-initialized during compile time, it is zero-initialized. At run time, the dynamic initialization happens for these statics that were zero-initialized.
Get hands-on with 1400+ tech skills courses.