I am currently going through the old version of Nicolai Josuttis' book on C++ templates. My question is regarding the initialization of static data members of the SortTracer
as implemented here.
Specifically, in tracer.hpp
, we have:
class SortTracer {
private:
int value; // integer value to be sorted
int generation; // generation of this tracer
static long n_created; // number of constructor calls
static long n_destroyed; // number of destructor calls
static long n_assigned; // number of assignments
static long n_compared; // number of comparisons
static long n_max_live; // maximum of existing objects
...
}
The initialization of the above static data members are done in tracer.cpp
:
#include "tracer.hpp"
long SortTracer::n_created = 0;
long SortTracer::n_destroyed = 0;
long SortTracer::n_max_live = 0;
long SortTracer::n_assigned = 0;
long SortTracer::n_compared = 0;
The test code is here:
#include "tracer.hpp"
...
int main()
{
// prepare sample input:
SortTracer input[] = { 7, 3, 5, 6, 4, 2, 0, 1, 9, 8 };
...
}
My question / confusion is this: does this program not suffer from static initialization order fiasco ? (which means, even though the program produces correct results at present, it is due to the fact that the initialization of the static data members in tracer.cpp
is the same as default initialization)
All global variables (including class-level statics) are guaranteed to be initialized before main()
. The order in which they are initialized between different source files is undefined.
Global Initialization Order Fiasco refers to the situation where global variables in one file are initialized with global variables from another source file, and the result depends on the initialization order. In your case, the variables are initialized with zero, so there is no "fiasco" - the program is safe.