4.14. Singleton Class

Singleton template class allows to turn any new or existing class T into a Singleton Pattern. It is accomplished by deriving class T from Singleton.


template <class T>
class Singleton
    static T* getInstance ();


4.14.2. USAGE

It is assumed that Singleton objects are long-lived. Often they exist for the life of the program. You delete them not so much to reclaim space but to shut down in an orderly manner (such as to return whatever resources derived class holds in its ownership back to the system). C++ deletes static objects automatically, although, it doesn't guarantee the calling order. In other words, destructor of Singleton class are not order-dependent.

To force the destruction order, Singleton class transfers ownership of object T to Destroyer class. When the program exits, the Destroyer class is destroyed, and the object T is destroyed along with it. Singleton destructor is now implicit.

In your class T header file, define T as follows:

// Name: T.h

#include <assa/Singleton.h>

class T : public Singleton<T>
    T ();

    foo ();

    // other methods ...

In your class T implementation file:

// Name: T.cpp

#include "T.h"

T* Singleton<T>::m_instance;
Destroyer<T> Singleton<T>::m_destroyer;

Now, a client of class T can call getInstance() to get an instance of class T from anywhere in the program like this:

void some_function ()
    T* anInstance = T::getInstance();
    anInstance->foo ();


Singleton class must be an immediate parent of class T.


Class T must have its default constructor T() defined in order for Singleton<>::getInstance() function to work.