Consider the following (artificial) example:
#include <iostream>
int f() {
return 42;
}
template <typename T>
struct S {
static int I;
};
template <typename T>
int S<T>::I = f();
template <typename T>
int g() {
return S<T>::I;
}
int global = g<int>();
int main() {
std::cout << global << std::endl;
}
It prints 0 when compiled with gcc 4.8.4 and run:
$ g++ test.cc
$ ./a.out
0
This suggests that dynamic initialization for global
is run before the initialization for S<T>::I>
. However, according to this SO answer,
objects defined in the same translation unit (usually it means .cpp file) are initialized in order of their definitions
Why is dynamic initialization for global
run before the one for S<T>::I>
and not in the order of their definitions and is it possible to force global
be initialized after?