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. 

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs.

 

 

Subscribe via E-Mail.

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 depends on the link-order of the object files. What can we do, when we don't have C++20 at our disposal? 

Lazy Initialization of static with local scope

Static variables with the 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 the 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: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Dominik Vošček, and Rob North.

 

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

Seminars

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

Bookable (Online)

German

Standard Seminars (English/German)

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

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

Mentoring

Stay Informed about my Mentoring

 

English 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

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 1151

Yesterday 4552

Week 42265

Month 186436

All 11667590

Currently are 164 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments