C++ Singleton Design Pattern

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

A Singleton is designed to ensure a class only has one instance and provides a global point of access to it. If you only require one instance or a convenient global point of access, but not both, consider other options before turning to the singleton.

Global variables can make it harder to reason about code. For example, if one of the calling functions isn't happy with the data it's receiving from a Singleton, you now have to track down what is first giving the singleton bad data in the first place.

Singletons also encourage coupling, a term used to describe two components of code that are joined together thus reducing each components own measure of self-containment.

Singletons aren't concurrency friendly. When a class has a global point of access, every thread has the ability to access it which can lead to deadlocks and race conditions.

Lastly, lazy initialization can cause performance issues if initialized at the wrong time. Removing lazy initialization also removes some of the features that do make Singleton's interesting in the first place, such as polymorphism (see Subclasses).

Sources: Game Programming Patterns by Robert Nystrom



Got any C++ Question?