Prevent static initialization order "fiasco", C++

The modern, more pattern-oriented way is not to use globals in the first place.

There's no other way around it.

It wouldn't be much of a "fiasco", otherwise!


The more usual way of addressing the problem is to avoid statics whenever possible - and even more so between objects that rely on construction order.

Then construct objects in the required order. For example, if we have two objects x and y, and construction of y will fail if x has not been constructed, then construct x first and supply it to the constructor (or another member) of y)

 SomeObject x;
 SomeOtherObject y(x);

or

 SomeObject *x = new SomeObject;
 SomeOtherObject y = new SomeObject(*x);   

(both of the above assume the constructor of y requires a reference).

If you need to share x and y between functions, simply pass them to functions as arguments.

If you must use statics (i.e. you don't want the typing of passing arguments everywhere) make the statics to be pointers, and initialise them once (for example, in main()).

//  all source files can use x and y via these declarations  (e.g. via a header file)

extern SomeObject *x;
extern SomeOtherObject *y;

//  definition in one source file only

SomeObject *x;
SomeOtherObject *y;

int main()
{
     x = new SomeObject;
     y = new SomeOtherObject(*x);

       // call other functions that use x and y.

     delete y;
     delete x;
}

But, really, it is best to avoid using statics if at all possible.


So my question is, is there any modern, more pattern oriented way to prevent this "fiasco" but to wrap the "static stuff" into functions???

In most cases, you can declare your "global" data in the main function, and use dependency injection to pass it around, where needed. In other words, do not have static state at all.

In practice, you can have situations where static data is needed. If there are no dependencies to other statics, make the static data const/constexpr.

// smart pointer that implements the "Foo" release policy
class FooPointer
{
    static const FooPointer NullFoo; // does not depend on other static values
    /* ... */
};

In case the static variables do depend on each other, just wrap them in static functions:

// smart pointer that implements the "Foo" release policy
class FooPointer
{
    static const FooPointer& NullFoo(); // depends on other static values
    /* ... */
};

To summarize:

Most (90%? 99%?) static/global/shared data should be dependency-injected into where it is used, and not created as static at all.

In the rare cases when statics are required for a reason or another and they do not depend on other statics, declare static variables.

In the very rare cases when statics need to be static and they depend on each other, wap them in static methods.

As a rule of thumb, if you have a lot of the second and third cases, you are not doing enough of the first.