Guide: Singletons


Singletons are a means of ensuring a single, unique copy of an object can ever exist. There are various ways of implementing singletons, the wikipedia has a surprisingly good article on singletons and provides a snippet that utilises the curiously recurring template pattern which is used as the derivation for this form of the singleton.

Compiling & Linking

Include the following at the top of any translation unit that requires compilation of a singleton derived class.

Since it is a template class, no linking is required if you are only using this class.



This singleton is intended to be inherited by a deriving class - this saves the work of actually reinventing the singleton mechanisms whenever you wish to use a singleton.

class TestObject : public ecl::Singleton<TestObject>
friend class ecl::Singleton<TestObject>;
int value() { return data; }
TestObject() : data(32) {}
int data;


If you use a macro as shown below, the instance can be conveniently and readably accessed,

#define Test TestObject::instance()
cout << Test.value() << endl;

Author(s): Daniel Stonier
autogenerated on Mon Jun 10 2019 13:08:28