I am trying to find a good way to ensure the construction and destruction order of static variables. As far as I know about static variables, they are constructed and destructed in the following ways:
Destruction order of static objects are in the reverse order of their construction.
If static variables are defined global space in different files, then their construction order is not guaranteed.
However, if a static variable is defined in a function, then local static variable is constructed when the first time execution hits its declaration.
Based on the rules above, I wrote the following c++ code to ensure static variable b
is always destructed before static variable a
, which in my experiment ensure the construction order and destruction order:
in file A.h
class A {
public:
SomeClass* GetStatic() {
static SomeClass a;
return &a;
}
}
in file B.h:
#include "A.h"
class B {
public:
AnotherClass* GetStatic() {
A::GetStatic(); // a dummy call to force the static local variable in
// A::GetStatic() get initialized before the b.
static AnotherClass b;
return &b;
}
}
In the above example, I put a dummy call A::GetStatic();
right before the declaration of static AnotherClass b;
. If rule 3 holds, this ensures a
is initialized before b
. And because of rule 1, it can be guaranteed that b
is destructed before a
.
And my questions are:
- Can I know whether what I've done is correct or might goes wrong in certain corner case?
- Is there a better or best way to ensure the construction or destruction order of static variables?
I also checked the isocpp.org website for the best way to ensure the construction and destruction order of static variables, but the section is still marked as TODO: WRITE THIS UP.