Solving the Static Initialization Order Fiasco with C++20

Contents[Show]

According to the FAQ of isocpp.org is the static initialization order fiasco "a subtle way to crash your program". The FAQ continues: The static initialization order problem is a very subtle and commonly misunderstood aspect of C++. ". Today, I write about this very subtle and misunderstood aspect of C++.  

TimelineCpp20

My short Disclaimer

Before I continue, I want to make a short disclaimer. Today's post is about variables with static storage duration and their dependencies. Variables with static storage duration may be global (namespace) variables, static variables, or static class members. In short, I call them static variables. Dependencies on static variables in different translation units are, in general, a code smell and should be a reason for refactoring. Consequently, if you follow my advice to refactor, you can skip the rest of this post. 

Static Initialization Order Fiasco

Static variables in one translation unit are initialized according to their definition order.

In contrast, the initialization of static variables between translation units has a severe issue. When one static variable staticA is defined in one translation unit and another static variable staticB is defined in another translation unit and staticB needs staticA to initialize itself, you end with the static initialization order fiasco. The program is ill-formed because you have no guarantee which static variable is initialized first at run-time (dynamic).

Before I talk about the rescue, let me show you the static initialization order fiasco in action.

A 50:50 Chance to get it Right

What is unique about the initialization of static variables? The initialization of static variables happens in two steps: static and dynamic. 

When a static cannot be const-initialized during compile-time, it is zero-initialized. At run-time, the dynamic initialization happens for these statics that are zero-initialized at compile-time. 

 

// sourceSIOF1.cpp

int quad(int n) {
    return n * n;
}

auto staticA  = quad(5); 

 

// mainSOIF1.cpp

#include <iostream>

extern int staticA;   // (1)
auto staticB = staticA;

int main() {
    
    std::cout << std::endl;
    
    std::cout << "staticB: " << staticB << std::endl;
    
    std::cout << std::endl;
    
}

 

The line (1) declares the static variable staticA. The initialization of staticB depends on the initialization of staticA. staticB is zero-initialized at compile-time and dynamically initialized at run-time. The issue is that there is no guarantee in which order staticA or staticB are initialized. staticA and staticB belong to different translation units. You have a 50:50 chance that staticB is 0 or 25. 

To make my observation visible, I change the link order of the object-files. This also changes the value for staticB!

 StaticInitializationOrderFiasco

What a fiasco!  The result of the executable depend on the link-order of the object files. What can we do, when we don't have C++20 to our disposal? 

Lazy Initialization of a static with local scope

Static variables with local scope are created, when they are used the first time. Local scope essentially means that the static variable is surrounded in some way by curly braces. This lazy creation is a guarantee that C++98 provides. With C++11, static variables with local scope are also initialized in a thread-safe way. The thread-safe Meyers Singleton is based on this additional guarantee. I already wrote a post about the "Thread-Safe Initialization of a Singleton". 

The lazy initialization can also be used to overcome the static initialization order fiasco.

// sourceSIOF2.cpp

int quad(int n) {
    return n * n;
}

int& staticA() {
    
    static auto staticA  = quad(5);   // (1)
    return staticA;
    
}

 

// mainSOIF2.cpp

#include <iostream>

int& staticA();           // (2)

auto staticB = staticA(); // (3)

int main() {
    
    std::cout << std::endl;
    
    std::cout << "staticB: " << staticB << std::endl;
    
    std::cout << std::endl;
    
}

 

staticA is, in this case, a static in a local scope (1). The line (2) declares the function staticA, which is used to initialize in the following line staticB. This local scope of staticA guarantees that staticA is created and initialized during run-time when it is the first time used. Changing the link order can, in this case, not change the value of staticB.

StaticInitializationOrderFiascoMeyers

Now, I solve the static initialization order fiasco using C++20.

Compile-time initialization of a static

Let me apply constinit to staticA. constinit guarantees that staticA is initialized during compile-time.

 

// sourceSIOF3.cpp

constexpr int quad(int n) {
    return n * n;
}

constinit auto staticA  = quad(5);  // (2)

// mainSOIF3.cpp

#include <iostream>

extern constinit int staticA;     // (1)

auto staticB = staticA;

int main() {
    
    std::cout << std::endl;
    
    std::cout << "staticB: " << staticB << std::endl;
    
    std::cout << std::endl;
    
}

(1) declares the variable staticA. staticA (2) is initialized during compile-time. By the way, using constexpr in (1) instead of constinit is not valid, because constexpr requires a definition and not just a declaration. 

 

Thanks to Clang 10 compiler, I can execute the program.

StaticInitializationOrderFiascoConstinit

As in the case of the lazy initialization with a local static, staticB has the value 25.

What's next?

C++20 has a few small improvements around Templates and Lambdas. In my next post, I present which ones.

Thanks a lot to my Patreon Supporters: Meeting C++, Matt Braun, Roman Postanciuc, Venkata Ramesh Gudpati, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Darshan Mody, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Wolfgang Gärtner, Jon Hess, Christian Wittenhorst, Louis St-Amour, Stephan Roslen, Venkat Nandam, Jose Francisco, Douglas Tinkham, Lakshman, Kuchlong Kuchlong, Avi Kohn, Serhy Pyton, Robert Blanch, Kuma [], Truels Wissneth, and Kris Kafka.

 

 

Seminars

I'm happy to give online-seminars or face-to-face seminars world-wide. Please call me if you have any questions.

Standard Seminars 

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

Contact Me

Modernes C++,

RainerGrimmSmall

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 2489

Yesterday 7957

Week 35011

Month 189606

All 4810500

Currently are 241 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments