Singleton

by Stephan Pareigis

Singleton

by Stephan Pareigis

A singleton is a class which controls the number of objects to be created from this class. Most often there shall be just a single object from a certain type. The basic principle to reach this is to limit the access to the constructor, i.e. making it private. There is a static function which allowes a single point of access to the single object.

Controversial discussion

There is a controversial discussion if a singleton is good design. The main critique is that it is reachable from any scope, thus appearing as a global variable. It is also not trivial to make it thread-safe (pre C++11). Destruction of a singleton is another issue. Also, lazy initialization might not be what you want in a time-critical system. I personally suggest in reactive time-critical systems to allocate your resources at start-up time if possible. This will guarantee by design that there is only a certain number of objects of a certain type. Also the initialization order may be established easliy. The objects shall communicate via appropriate communication channels.

Issues

There are a couple of issues to think about when deciding to use a singleton and choosing the right implementation.

  • threadsafety of a singleton. There is the DCLP (double checked locking pattern) [1] to make the original GOF singleton [2] thread-safe. As recovered several years later, this may fail under certain circumstances [3]. In C++11 there is a thread-safe implementation due to a new memory model. The Meyers Singleton [5] is also thread-safe in C++11.

  • destruction. The original GOF singleton cannot be destructed. At the end of the program it doesn´t free its resources. The Meyers Singletons destructor is called at the programs end. If you need to destroy a singleton during runtime and re-create it later, the phoenix singleton [6] comes in handy.

References

[1] D.C. Schmidt, T.Harrison; Double-Checked Locking; Pattern Languages of Program Design 3, 1997 [2] E.Gamma, R.Johnson, R.Helm, J.Vlissides; Design Pattern; Prentice Hall 1994 [3] S.Meyers, A.Alexandrescu; C++ and the Perils of Double-Checked Locking; 2004 [4] H.Sutter; herbsutter.com [5] S.Meyers; More Effective C++; 1996 [6] A.Alexandrescu; Modern C++ Design, Addison-Wesley, 2001

Related