TimelineCpp20

Solving the Static Initialization Order Fiasco with C++20

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 generally 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, 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 discussing the rescue, let me show you the static initialization order fiasco.

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 is zero-initialized at compile-time. 

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

     

    // 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;
        
    }
    

     

    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 used for 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“. 

    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, static in a local scope (1). 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 will 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, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery,and Matt Godbolt.

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

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

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

    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++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *