Static initialization is well described subject, here and even at this site here
And everywhere it is written that problem will occurs if there exists different compilation units with related static variables. And if static variables exists in one compilation unit, there shouldn't be problem: they will be initialized in order of their position in file.
But I have this code:
template <typename T>
class A{
public:
int _data;
T _obj;
A(int data) :_data(data){}
};
template <typename T>
class B{
public:
const static B<T> nullObj;
B(int data) :_a(new A<T>(data)){}
A<T> *_a;
};
template <typename T>
class C{
public:
const static C<T> nullObj;
C() :_a(nullObj._a){}
C(bool t) :_a(B<T>::nullObj._a){
_a->_data++; //FAILS HERE!
}
A<T> *_a;
};
template <typename T>
const B<T> B<T>::nullObj(0);
template <typename T>
const C<T> C<T>::nullObj(false);
class _B{};
class _A{ public: _A(){}; C<_B> g; };
int main(){
return 0;
}
And it fails at runtime before entering main() function, because it tries to initialize const C<T> C<T>::nullObj(false);
before const B<T> B<T>::nullObj(0);
is initialized. Despite their position in one file.
Why does it tries to initialize second static variable before first static variable? Does there exist chapter in C++ Standart where described real situation with sequence of static initialization?