3

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;
user1899020
  • 13,167
  • 21
  • 79
  • 154

2 Answers2

5

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
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.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132