The static initialization problem is known as the static initialization of the fiasco order :
In short, suppose you have two static objects x and y that exist in separate source files, say x.cpp and y.cpp. Suppose further that initialization for an object y (usually a constructor of y-objects) calls some method for an object x.
So, if you have another translation unit using your constants, you have a pretty good chance that your program will not work. Sometimes it’s that the files are linked to each other, some formats even define it in the document (I think Solaris is one example here).
The problem also applies to built-in types such as int. Example from the FAQ:
#include <iostream> int f(); // forward declaration int g(); // forward declaration int x = f(); int y = g(); int f() { std::cout << "using 'y' (which is " << y << ")\n"; return 3*y + 7; } int g() { std::cout << "initializing 'y'\n"; return 5; } int main() { std::cout << x << std::endl << y << std::endl; return 0; }
If you run this example, the output will be:
using 'y' (which is 0) initializing 'y'
So y first gets zero initialization, and then constant initialization (?) Is done.
The solution is Build the first time you use the idiom :
The main idea of Constio on First Use Idiom is to wrap a static object inside a function.
Static local objects are created when the control flow is first accessed.
source share