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:
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.
In your case you are using construct on first use, and none of the constructors of your classes dependent on the other. Thus the order of initialization is guaranteed A then B.
The destruction order in this case it is guaranteed to be as such B->A, as long as you have simple destructors. Here is a more elaborate answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With