3

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;
Flow
  • 23,572
  • 15
  • 99
  • 156
user1899020
  • 13,167
  • 21
  • 79
  • 154

2 Answers2

6

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.

SirGuy
  • 10,660
  • 2
  • 36
  • 66
Mark B
  • 95,107
  • 10
  • 109
  • 188
  • Wow. So the short answer is unfortunately `no`. Thanks. I have a new related question here: http://stackoverflow.com/questions/18834855/can-the-compiler-deal-with-the-initialization-order-of-static-variables-correctl – user1899020 Sep 16 '13 at 18:26
1

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.

Taylor Brandstetter
  • 3,523
  • 15
  • 24