The Singleton pattern models a class for which an application may have at most one object. It also provides a controlled access point to that object. A printer spooler or a single stadium executive pass illustrates the requirement: every request reaches the same object. section 14.0 section 14.1
A sound singleton design must:
- Provide an access operation that always returns the same object. section 14.1.1
- Create the object automatically when first requested, rather than requiring the application to create it. section 14.1.1
- Avoid creating the object when it is never requested. section 14.1.1
- Prevent copying so assignment and the copy constructor cannot produce additional instances. section 14.1.3
Refactoring ExecutivePass
A global ExecutivePass seems simple, but callers can copy it, producing independent passes with different keys. Global state also permits unexpected changes, creates order-of-initialization problems, and keeps the pass alive even when unused. Refactor it by making the constructor private, deleting the copy constructor and copy assignment operator, and storing the sole pointer in a private static member. A public static obtain(holder) function creates the object when the pointer is nullptr, updates its holder, and returns it. Deleting the object resets the pointer, allowing later creation. Ron and Sal therefore receive the same key; after deletion, Bob and Flo share a newly created key. section 14.1.2 section 14.1.3
The generic structure replaces ExecutivePass with Singleton, single_instance with singleton, obtain() with get_singleton(), and application-specific data and operations with generic members. The pattern controls construction and copying, but its check-then-create operation needs extra care in multithreaded programs: simultaneous callers can create multiple objects. section 14.1.4 section 14.4
Figure 14.2 A well-designed singleton object. The constructor is private. The copy constructor and the copy assignment operator are both disabled. The static private member variable single_instance points to the singleton object, and the static public member function obtain() returns the value of the pointer.
Use the class diagram to see how the private constructor, disabled copy operations, static instance pointer, and public access function enforce the design. section 14.1.3





