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 translation unitsA translation unit is the source file after processing of the C preprocessor. The C preprocessor literally includes the header files using ‘include’ directives, performs conditional inclusion with directives such as ‘ifdef’, or ‘ifndef’, and expands macros. The compiler uses the translation unit to create an object file. are, in general, a code smell and should be a reason for refactoring. Consequently, if you follow my advice to refactor, you can skip this section.

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 1200+ tech skills courses.