问题
How about the following case? Can the compiler deal with the initialization order of static variables correctly if there is dependency?
a.h
template<class T>
struct A { static double a; };
template<class T>
double A<T>::a = 1;
b.h
struct B { static double b; };
b.cpp
#include "b.h"
#include "a.h"
double B::b = A<int>::a;
回答1:
In your example, A<int>::a
is initialized statically, and all static initialization takes place before any dynamic initialization. B::b
is initialized dynamically and so it will happen after A<int>::a
is initialized, and everything is fine.
回答2:
In this case, there is no issue since a
is initialised statically; this is guaranteed to happen before the dynamic initialisation of b
.
More generally, where both require dynamic initialisation, this is an issue. Unless you specialise the template member before using it to initialise b
, there is no guaranteed order. To quote the standard (C++11 3.6.2/2):
Definitions of explicitly specialized class template static data members have ordered initialization. Other class template static data members (i.e., implicitly or explicitly instantiated specializations) have unordered initialization.
来源:https://stackoverflow.com/questions/18834855/can-the-compiler-deal-with-the-initialization-order-of-static-variables-correctl