Now, I'm concerned on my own code. Will I hit the initialization order
fiasco on this code?
No. The static initialisation order fiasco is an issue when you have
*two* different static objects (e.g. obj1 and obj2) defined in
*different* source files *and* your code relies on one being
constructed before the other (e.g. during construction of obj1, obj1
calls a member function obj2). The problem is that there is no way you
can control which of obj1 and obj2 is constructed first, but if obj1
happens to be constructed first there is no obj2 yet for it to use.
Bang - you're dead.
Your code below only contains one static object, A::x, of type B.
// A.h
class B;
class A {
private:
static B x;
public:
static void f();
};
// A.cpp
#include "A.h"
#include "B.h" // details irrelevant, assume
// void B::do_something() exists
B A::x;
void A::f()
{
x.do_something();
// do other stuff
}
// main.cpp
#include "A.h"
int main()
{
It is guaranteed that, by the time you enter main here, A::x is fully
constructed, therefore the call to A::f() below, which in turn calls a
member function of A::x, is fine.
What would be a problem would be if you had something like this (not
tested):
// C.h
#include "A.h"
class C
{
public:
// Constructor indirectly calls do_something() on A::x
C() { A::f(); }
};
and you changed main.cpp to
#include "A.h"
#include "C.h"
C c;
int main()
{
A::f();
}
Now A::x and c are defined in different translation units and you have
no control over which is constructed first. But the construction of c
involves calling do_something() on A::x. So if the compiler happens to
choose to construct c first, you suffer death by fiasco.
Gavin Deane