问题
Can the compiler deal with the initialization order of static variables correctly if there is dependency? For example, I have
a.h
:
struct A { static double a; };
a.cpp
:
#include "a.h"
double A::a = 1;
b.h
:
struct B { static double b; };
b.cpp
:
#include "b.h"
#include "a.h"
double B::b = A::a;
回答1:
Within translation units the order of such initialization is specified. Across translation units the order is not specified.
So in your case, since statics will get zero initialized by default, B::b
will definitely be 0 or 1.
回答2:
Nope. Static initialization order is undefined by the C++ standard. You can HOPE that your compiler is smart, but there's no guarantee.
Think about what would happen if you also have a "c" variable which is assigned with "b", and the "a" variable is assigned with "c". Then you've have a circular dependency, and it would compile, but you would end up with garbage values.
来源:https://stackoverflow.com/questions/18834548/can-the-compiler-deal-with-the-initialization-order-of-static-variables-correctl