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.
The Singleton Pattern is a creational pattern. Here are the facts:
- Guarantees that only one instance of a class exists
- You need access to some shared resource
- This shared resource must exist only once
- Boost serialization defines a template “which will convert any class into a singleton with the following features“: https://www.boost.org/doc/libs/1_80_0/boost/serialization/singleton.hpp
- It performs its job by deriving from the class boost::noncopyable:
- A private instance of Singleton
- A public member function that returns an instance
- Creates the instance
- 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++.
- The creational patterns Abstract Factory, Builder, and Prototype are often singletons.
- The structural pattern Facade is often a singleton.
In the following lines, I discuss various implementation variants of the Singleton. Let me start with the classical implementation of the Singleton Pattern.
Here is the implementation, based on the “Design Patterns: Elements of Reusable Object-Oriented Software” (Design Patterns) book:
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
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:
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
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.
Line (1) declares the static variable
staticA. The following initialization of
staticB depends on the initialization of
staticB is zero-initialized at compile time and dynamically initialized at run time. The issue is that there is no guarantee in which order
staticB are initialized because
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
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.
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.
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.
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, 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, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, and Philipp Lenk.
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|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
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++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,