The Singleton

Contents[Show]

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)

  • 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++.

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, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Evangelos Denaxas, 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, and Wolfgang Fütterer.

 

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

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC 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.

New

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

 

 

 

Comments   

0 #1 Ernst 2022-09-20 07:08
hi
is there full diagram with a topics you are discussing in your posts?

we see some piece of this in the begining of most (all?) posts, but would be very interesting to review full version of this. to understand your view of structure for the learning/teaching C++

thank you
Quote

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)

Blog archive

Source Code

Visitors

Today 5425

Yesterday 4232

Week 5425

Month 16354

All 10359661

Currently are 171 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments