C++ guarantees that variables in a compilation unit (.cpp file) are initialised in order of declaration. For number of compilation units this rule works for each one separat
A robust solution is to use a getter function that returns a reference to an static variable. A simple example is shown below, a complex variant in our SDG Controller middleware.
// Foo.h
class Foo {
public:
Foo() {}
static bool insertIntoBar(int number);
private:
static std::vector& getBar();
};
// Foo.cpp
std::vector& Foo::getBar() {
static std::vector bar;
return bar;
}
bool Foo::insertIntoBar(int number) {
getBar().push_back(number);
return true;
}
// A.h
class A {
public:
A() {}
private:
static bool a1;
};
// A.cpp
bool A::a1 = Foo::insertIntoBar(22);
The initialization would being with the only static member variable bool A::a1
. This would then call Foo::insertIntoBar(22)
. This would then call Foo::getBar()
in which the initialization of the static std::vector
variable would occur before returning a reference to the initialized object.
If the static std::vector
were placed directly as a member variable of the Foo class
, there would be a possibility, depending on the naming ordering of the source files, that bar
would be initialized after insertIntoBar()
were called, thereby crashing the program.
If multiple static member variables would call insertIntoBar()
during their initialization, the order would not be dependent on the names of the source files, i.e., random, but the std::vector
would be guaranteed to be initialized before any values be inserted into it.