0

I read this and I can't think of a scenario for which X::_x will be used before initialized in file X.cpp (assuming the compiler treats X.h and X.cpp one after the other)

Can someone explain to me how such scenario could happen?

McLovin
  • 3,295
  • 7
  • 32
  • 67

2 Answers2

6

Static initialization order fiasco happens when you have multiple translation units* that use static initialization, and one of the initialization routines require data produced by another one.

If all you have is a single header and a single translation unit, static initialization order fiasco does not apply, because initialization order within the same unit is well defined (it follows the order of declaration).

* that's a fancy name for a cpp file.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Isn't this rather object created by a single compilation run e.g. `g++ -c a.cc b.cc -o ab.o` would give a single translation unit? – W.F. Jul 01 '16 at 15:02
  • 1
    @W.F.: No, that's two translation units. I guess g++ would write them to the same .o file, the second clobbering the first. According to the documentation, "Since only one output file can be specified, it does not make sense to use -o when compiling more than one input file, unless you are producing an executable file as output." – Fred Larson Jul 01 '16 at 15:07
  • @W.F. It does not matter if you compile both cc files in one go: from the point of view of C++ standard, each cc file is considered a separate translation unit. – Sergey Kalinichenko Jul 01 '16 at 15:09
0

I think it cannot happen with just the code on the page, however there may be more code, behaving as described on the page. In one of these files, one could have a static object of type X:

// File X3.cpp
#include "X.h"

X x__;

Now, if:

  • the default constructor of the class X calls someMethod

    // File X2.cpp
    
    X::X() {
      someMethod();
    }
    

and

  • x__ is initialized before x_ (which may or may not happen, since both are static objects in different cpp files the order is undefined)

then someMethod() will be called before x_ has been initialized.

Ghislain Fourny
  • 6,971
  • 1
  • 30
  • 37