Library/C++/Use Singletons not Globals

The Argument Against Global Variables
The general advice for not using global variables is this: a global variable is accessible from anywhere in the program. Therefore, in a large, complex (particularly multi-threaded), application it can become very difficult to know what other code in the application could be changing the global variables value. As a consequence it is difficult to confidently define the exact conditions under which it is safe to read from or write to that variable.

One could argue that "good" programmers should know better than to modify such a variable in a subtle or undocumented manner, but what happens in the case of a large organization composed of both expert and novice programmers working on the same code base?

One of the very purposes of access-control mechanisms in programming languages is to allow programmers to have the compiler enforce as many of the good practices and policies as possible so novices must go out of their way to use part of the system incorrectly.

Ok, but why are Singleton's any better than a regular global variable?

First, we'll presume the reader is familiar with the.

Basic OOP Advantages
For the purposes of this article, we'll assume a Singleton is a C++ class - not a C++ primitive (like an ).

A object allows the data members to be encapsulated in accessor and mutator (i.e. getter / setter) methods. This offers the first advantage. The accessor / mutator pair can add logic to do some sanity checking to make sure that the variable is being modified in a consistent manner. It also affords the opportunity to later add new methods for perhaps adding locks to the data or a stack of values allowing the current value to be pushed or popped. This of course is just the advantages of using an object rather than a POD (plain-old data) type; but, as the notion of a Singleton usually implies a class rather than plain data, so we'll bundle this in as an advantage.

Well-Defined Construction / Destruction Points
More importantly perhaps is that the Singleton allows control over exact specification of when the object is created and when it is deleted. Note: the order of construction and destruction of global variables, especially when considering applications with dynamic libraries and "DLL startup routines" is not at all clear. There also restrictions on what can legally be done in the code during such load-time initialization. Having a clear, unambiguous construction time (the first acquisition of the Singleton) can be advantageous to large applications.