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.
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
- 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:
class BOOST_SYMBOL_VISIBLE singleton_module : public boost::noncopyable { ... };
Structure
instance
(static)
- A private instance of Singleton
getInstance (static)
Modernes C++ Mentoring
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
- The creational patterns Abstract Factory, Builder, and Prototype are often singletons.
- The structural pattern Facade is often a singleton.
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
.
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
!
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, 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, Matt Godbolt, and Honey Sukesan.
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 |
Modernes C++ GmbH
Modernes C++ Mentoring (English)
Rainer Grimm
Yalovastraße 20
72108 Rottenburg
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org
Modernes C++ Mentoring,
Leave a Reply
Want to join the discussion?Feel free to contribute!