wiki:cpp-static-initialization-order-fiasco
Table of Contents
C++ Static initialization order fiasco
Static initialization order fiasco occurs when a static variable in one translation unit depends on a static variable in another, but their initialization order is undefined. If the dependency initializes first, it uses an uninitialized global, causing undefined behavior.
Avoid this by using local static variables (initialized on first use) or by carefully designing which globals depend on which.
Example
This example shows the fiasco and a safe workaround using function-local statics.
// compile: g++ -o fiasco fiasco.cpp // run: ./fiasco // description: static initialization order fiasco and local static workaround #include <iostream> #include <vector> // Unsafe: initialization order undefined // std::vector<int> global_vec; // int size_on_init = global_vec.size(); // Safe: use function-local static (initialized on first call) const std::vector<int>& getGlobalVec() { static std::vector<int> global_vec{1, 2, 3}; return global_vec; } int getSizeOnInit() { static int size = getGlobalVec().size(); // safe: called after vec initialized return size; } int main() { std::cout << "Size: " << getSizeOnInit() << "\n"; return 0; }
wiki/cpp-static-initialization-order-fiasco.md · Last modified: by 127.0.0.1
