WORKSPACE_A.cpp/.h
Class WORKSPACE_A {
static AAA a;
}
WORKSPACE_B.cpp/.h
Class WORKSPACE_B {
static BBB b;
}
How do I know whether AAA a , or BBB b is initialized first.
Thank you
WORKSPACE_A.cpp/.h
Class WORKSPACE_A {
static AAA a;
}
WORKSPACE_B.cpp/.h
Class WORKSPACE_B {
static BBB b;
}
How do I know whether AAA a , or BBB b is initialized first.
Thank you
As stated by @Denny the issue is probably dependencies between the twos.
I think the way to go is having pointers and explicit static init functions:
class WORKSPACE_A {
static AAA* a;
public:
static void initialize() { /* a = ... */ }
}
class WORKSPACE_B {
static BBB* b;
public:
static void initialize() { /* b = some_f(WORKSPACE::a) */ }
}
This is called the "static initialization order fiasco"
A common approach is to use initialize-on-first-use within an "accessor function"
class WORKSPACE_A {
AAA& getA()
{
static AAA a;
return a;
}
}
Of course, you still have "static destruction order fiasco" to contend with... This can be mitigated by dynamically allocating the AAA in the accessor (static AAA *a = new AAA;
) but then the object simply never gets destructed!
Order of initialization of global variables (or static) are guaranteed in each translation unit. But not guaranteed in different translation units.
See this answer to the question C++ global initialization order ignores dependencies?.