CreationalPatterns

The Singleton

The most controversial Design Pattern from the book  “Design Patterns: Elements of Reusable Object-Oriented Software” is the Singleton Pattern. Let me introduce it before I discuss its pros and cons.

 

CreationalPatterns 

The Singleton Pattern is a creational pattern. Here are the facts:

Singleton Pattern

Purpose

  • Guarantees that only one instance of a class exists

Use Case

  • You need access to some shared resource
  • This shared resource must exist only once

Example

class BOOST_SYMBOL_VISIBLE singleton_module :
    public boost::noncopyable
{
  ...
};

Structure

 SingletonStructure

 

instance (static)

  • A private instance of Singleton

getInstance (static)

 

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.

     

    • A public member function that returns an instance
    • Creates the instance

    Singleton

    • Private constructor

     

    Calling the member function getInstance is the only way to create a Singleton. Additionally, the Singleton must not support copy semantics.

    This brings me to its implementation in modern C++.

    Related Patterns

    Implementation

    In the following lines, I discuss various implementation variants of the Singleton. Let me start with the classical implementation of the Singleton Pattern.

    Classical Implementation

    Here is the implementation, based on the “Design Patterns: Elements of Reusable Object-Oriented Software” (Design Patterns) book:

    // singleton.cpp
    
    #include <iostream>
    
    class MySingleton{
    
      private:
        static MySingleton* instance;                            // (1)
        MySingleton() = default;
        ~MySingleton() = default;
    
      public:
        MySingleton(const MySingleton&) = delete;
        MySingleton& operator=(const MySingleton&) = delete;
    
        static MySingleton* getInstance(){
          if ( !instance ){
            instance = new MySingleton();
          }
          return instance;
        }
    };
    
    MySingleton* MySingleton::instance = nullptr;                // (2)
    
    
    int main(){
    
      std::cout << '\n';
    
      std::cout << "MySingleton::getInstance(): "<< MySingleton::getInstance() << '\n';
      std::cout << "MySingleton::getInstance(): "<< MySingleton::getInstance() << '\n';
    
      std::cout << '\n';
    
    }
    

     

    The original implementation used a protected default constructor. Additionally, I explicitly deleted copy semantics (copy constructor and copy assignment operator). I will write more about copy semantics and move semantics later.

    The output of the program shows that there is only one instance of the class MySingleton.

    singleton

    This implementation of the Singleton requires C++11. With C++17, the declaration (line 2) and definition (line 2) of the static instance variable instance can be directly done in the class:

    class MySingleton{
    
      private:
        inline static MySingleton* instance{nullptr};  // (3)
        MySingleton() = default;
        ~MySingleton() = default;
    
      public:
        MySingleton(const MySingleton&) = delete;
        MySingleton& operator=(const MySingleton&) = delete;
    
        static MySingleton* getInstance(){
          if ( !instance ){
            instance = new MySingleton();
          }
          return instance;
        }
    };
    

     

    Line 3 performs the declaration and definition in one step.

    What are the weaknesses of this implementation? Let me name the static initialization order fiasco and concurrency.

    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 up 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.

    For completeness: Static variables are initialized according to their definition order and destructed in the reverse order. Accordingly, no ordering guarantees are provided for initialization or destruction between translation units. The translation unit is what to get after the preprocessor run. 

    What does this have to do with Singletons? Singletons are statics in disguise. When, therefore, one Singleton’s initialization depends on another Singleton’s initialization in another translation unit, you could end in the static initialization order fiasco.
    Before I write about the solution, 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 statics? The initialization order of statics happens in two steps: at compile time and at run time.

    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 were zero-initialized.

    // sourceSIOF1.cpp
    
    int square(int n) {
        return n * n;
    }
    
    auto staticA  = square(5); 
    

     

    // mainSOIF1.cpp
    
    #include <iostream>
    
    extern int staticA;                  // (1)
    auto staticB = staticA;     
    
    int main() {
        
        std::cout << '\n';
        
        std::cout << "staticB: " << staticB << '\n';
        
        std::cout << '\n';
        
    }
    

     

    Line (1) declares the static variable staticA. The following initialization of staticB depends on the initialization of staticA. But 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 because staticA and staticB belong to different translation units. You have a 50:50 chance that staticB is 0 or 25.

    To demonstrate this problem, I can 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?

    The Meyers Singleton

    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 initialization is a guarantee that C++98 provides. The Meyers Singleton is exactly based on this idea. Instead of a static instance of type Singleton, it has a local static of type Singleton.

    // singletonMeyer.cpp
    
    #include <iostream>
    
    class MeyersSingleton{
    
      private:
    
        MeyersSingleton() = default;
        ~MeyersSingleton() = default;
    
      public:
    
        MeyersSingleton(const MeyersSingleton&) = delete;
        MeyersSingleton& operator = (const MeyersSingleton&) = delete;
    
        static MeyersSingleton& getInstance(){
          static MeyersSingleton instance;        // (1)
          return instance;
        }
    };
    
    
    int main() {
    
      std::cout << '\n';
    
      std::cout << "&MeyersSingleton::getInstance(): "<< &MeyersSingleton::getInstance() << '\n';
      std::cout << "&MeyersSingleton::getInstance(): "<< &MeyersSingleton::getInstance() << '\n';
    
      std::cout << '\n';
    
    }
    

     

    static MeyersSingleton instance in line (1) is a static with local scope. Consequentially, it lazy initialized and can not be a victim of the static initialization order fiasco. With C++11, the Meyers Singleton become even more powerful.

    Concurrency

    With C++11, static variables with local scope are also initialized in a thread-safe way. This means that the Meyers Singleton does not only solve the static initialization order fiasco, but also guarantees that the Singleton is initialized in a thread-safe way. Additionally, using the locals static for the thread-safe initialization of a Singleton is the easiest and fastest way. I have already written two posts about the thread-safe initialization of the Singelton.

    What’s Next?

    The Singleton Pattern is highly emotional. My post “Thread-Safe Initialization of a Singleton” was so far read by more than 300’000 people. Let me, therefore, discuss in my next posts the pros and cons of the Singleton and possible alternatives.

     

     

     

     

     

    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, 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, 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, moon, Philipp Lenk, Hobsbawm, and Charles-Jianye Chen.

    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 *