This is optional.
While we normally design classes so that the user may construct any number of independent instances, there are circumstances where it is desirable to have only one instance of a class that is shared by all components of a program. Examples include an object storing configuration parameters, an object recording events during the execution of a program, or an object communicating with a particular physical device.
Rather than declaring a global variable, we can modify the design of a class so that the class itself is responsible for restricting the number of instances that may be constructed and for providing access to its sole instance. This is referred to as the singleton design pattern.
Before reading the design document, we will introduce one additional feature of the C++ programming language: a static local variable of a function.
Normally, a local variable is initialized each time execution reaches its declaration and is destroyed when execution leaves its scope. By declaring a local variable using the static keyword, however, we can have a variable that retains its value between successive calls to the function.
Consider the following program, which you are encouraged to compile and execute:
#include <iostream>
int f();
int g();
int main() {
std::cout << "f g" << std::endl;
for ( int k{0}; k < 5; ++k ) {
std::cout << f() << " "
<< g() << std::endl;
}
return 0;
}
int f() {
int n{ 0 };
// Increment 'n' and return the incremented value
return ++n;
}
int g() {
static int n{ 0 };
// Increment 'n' and return the incremented value
return ++n;
}
The output of this program is:
f g 1 1 1 2 1 3 1 4 1 5
Each call to f() introduces a new local variable initialized to zero. In contrast, the static local variable in g() is initialized only once and retains its value between successive calls to the function.
Note that both variables have local scope: neither variable may be accessed by name outside the function in which it is declared. The difference is in their lifetimes. The static local variable continues to exist even after the function returns.
In this design document, we start with a simple Counter class that allows the user to construct any number of independent counters. We then consider how private constructors and destructors, deleted member functions, a public static member function, and a static local variable may be combined to convert this class into a singleton.
Of particular interest is that we do not need to modify the implementations of any of the original overloaded operators. Instead, our modifications focus on controlling the construction, destruction, and accessibility of instances of the class. This can be seen by comparing the implementation of the counter class as a default in Counter.* versus the implementation of a singleton in Counter_singleton.* in the source directory.