Finding C++ Static Initialization Order Problems

Can the static initialization order fiasco occur in C programs?

Static initialization in C does not have the same problems that C++ has.

In C, objects with static storage duration may only be initialized via constant expressions, i.e. values that can be computed at compile time, so there are no issues that can arise regarding order of initialization.

In contrast, C++ allows calling functions to initialize static objects, and the order in which those functions are called are not well-defined.

C++ static initialization order

You have answered your own question. Static initialization order is undefined, and the most elegant way around it (while still doing static initialization i.e. not refactoring it away completely) is to wrap the initialization in a function.

Read the C++ FAQ items starting from https://isocpp.org/wiki/faq/ctors#static-init-order

Determine static initialization order after compilation?

Matthew Wilson provides a way to answer this question in this section (Safari Books Online subscription required) of Imperfect C++. (Good book, by the way.) To summarize, he creates a CUTrace.h header that creates a static instance of a class that prints the filename of the including source file (using the nonstandard preprocessor macro __BASE_FILE__) when created, then he includes CUTrace.h in every source file.

This requires a recompilation, but the #include "CUTrace.h" can easily be added and removed via a script, so it shouldn't be too hard to set up.

Question regarding Static Initialization Order Fiasco

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.

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!



Related Topics



Leave a reply



Submit