From time to time you will need the singleton pattern in games programming. A singleton restricts the instantiation of a class to one object.

In C++ there are various ways of implementing it. In my NDS game project I implemented it using a template.

I prefer this implementation over others, because it’s very simple to use and works well:

This is the template:

#include <cassert>

template <typename T> class Singleton {
    static T* instance;
public:
    Singleton() {
        assert(!instance);
    }

    ~Singleton();

    static T* Get() {
        if (!instance)
            instance = new T();
    
        return instance;
    }
};

template <typename T> T *Singleton <T>::instance = NULL;

You can use it this way:

class MySingleton : public Singleton<MySingleton> {
public:
    int someValue;
};

// [ ........ ]

MySingleton::Get()->someValue = 4;
std::cout << MySingleton::Get()->someValue << endl;
  1. Luiz Alvarez (2010-12-13 12:00)

    I dont like a template based implementation because nasty things could happen. For example, this code is perfectly legal and runs without errors:Singleton<MySingleton> *s0 = new Singleton<MySingleton>(); MySingleton *s1 = new MySingleton(), *s2 = new MySingleton(); MySingleton::Get()->someValue = 4; MySingleton *s3 = new MySingleton(*MySingleton::Get());s1->someValue = 0; s2->someValue = 1; s3->someValue = 2; MySingleton::Get()->someValue = 3;

  2. joe (2010-12-14 03:36)

    @Luiz Yes, you’re right. I never thought of this before. One possibility is to declare the constructor in the base class protected and use “friend class” in the derived class.Do you prefer a a macro-based system or do implement each singleton-classes on their own?

  3. physiotherapy (2011-01-19 19:55)

    Thank you, I have recently been searching for information about this topic for ages and yours is the best I have discovered so far.

Add your comment now