Hack of the day: A Singleton in C++
December 13, 2010
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;
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;
@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?
Thank you, I have recently been searching for information about this topic for ages and yours is the best I have discovered so far.