Solve SIOF (Static Initialization Order Fiasco) with Meyer's Singleton.
Xiahua Liu January 14, 2025 #LinuxWhat is SIOF?
The Static Initialization Order Fiasco (SIOF) is a common C++ issue that occurs when initialization order of static objects across different translation units is undefined. As explained in the C++ standard:
The static initialization order fiasco refers to the ambiguity in the order that objects with static storage duration in different translation units are initialized in.
A Simple SIOF Example
// filepath: a.cpp
;
static A globalA; // Static object in first translation unit
// filepath: b.cpp
extern A globalA; // Reference to static object from a.cpp
;
static B globalB; // Problem: Order of initialization is undefined
Understanding Initialization Stages
There are two key stages in initializing non-local objects:
1. Static Initialization
- Constant Initialization: Applied to
const
/constexpr
static objects. - Zero Initialization: Applied to other non-local static/thread-local variables.
2. Dynamic Initialization
Occurs in two possible ways:
- Early Dynamic: Happens before
main()
. - Deferred Dynamic: Happens after the first usage.
The Solution: Deferred Initialization
To avoid SIOF, we should use deferred initialization for all the non-const static variables. Here's a practical example:
// filepath: a.cpp
;
// filepath: b.cpp
;
It is called Meyer's Singleton.