3 Tips for Using Singletons in C++ | by Josh Weinstein | Feb, 2022

Encapsulation logic, deferred and dynamic initialization, and ordered dynamic initialization

Josh Weinstein
Photo by Federico Beccari on Unsplash

First, let’s define what exactly a singleton is. A singleton is an object with only a single instance that exists within a program. Typically, it cannot be destructed, and lives until the end of the program once constructed.

Main Thread:  0x105bf3dc0Constructed by: 0x700007865000

Singletons allow grouping and encapsulation of global access patterns that would be very difficult to do without them.

In terms of static data variables and members, there are two main types of initialization. Deferred initialization is what we described earlier, that a given variable will be initialized the first time it is accessed.

There’s one important exception toward the definition of dynamic initialization. You may have noticed that compiling and running the program with Registrar and Member objects doesn’t run into problems.

Leave a Comment