HomeC&C++WainTutorialsSamplesTip & TrickTools


A singleton is a class which is can only exist in one instance, and is created by itself when needed.
One use for this is data storage, e.g. a database or a windows registry. Another usage of singletons is when mulitble static constructors needs to access the same shared object, e.g. a logfile; we can't predict which constructor will be called first.
The basics:
class Singleton
{
public:
   static Singleton &GetInstance();
   static void KillInstance();
protected:
   static Singleton *Me;
   Singleton()
   {}
   ~Singleton()
   {}
};
Singleton *Singleton::Me;
Then, when the user needs access to the instance he will call GetInstance, e.g (S, is a std::sting member of Singleton):
int main()
{
   Singleton::GetInstance().S = "Singleton test";
   std::cout << Singleton::GetInstance().S << std::endl;
   Singleton::KillInstance();
}
To implement GetInstance and KillInstance:
class Singleton
{
public:
   static Singleton &GetInstance()
   {
      if(!Me)
         Me = new Singleton;
      return *Me;
   }
   static void KillInstance()
   {
      delete Me;
      Me = 0;
   }
The constructor for Singleton is protected, to avoid that the users tries to create there own instance of the class.
To make it even more safe we add private assignment and copy operators, and destructor:
private:
   Singleton &operator = (const Singleton &);
   Singleton(const Singleton &);
   ~Singleton()
   {}
We don't implement them, we just don't the user to use them.
We could implement the singleton this way:
#include <iostream>
#include <string>

class Singleton
{
public:
   static Singleton &GetInstance()
   {
      static Singleton Me;
      return Me;
   }
   std::string S;
private:
   Singleton &operator = (const Singleton &);
   Singleton(const Singleton &);
   Singleton()
   {}
   ~Singleton()
   {}
};

int main()
{
   Singleton::GetInstance().S = "Singleton test";
   std::cout << Singleton::GetInstance().S << std::endl;
}
This is fine, as we don't need to remember to delete the object when done, by calling KillInstance. But it will not work if your singleton's constructor is to do anything, and GetInstance is called from a static constructor, as we don't know which static constructor is called first.