How to implement singleton

Singleton is a design patterns, that restricts that object has only one instance.

There are 3 most important things related to singleton:

  • must have public static method that returns the instance of class
  • must have private constructor
  • must have private static variable that points to instance of class

class Logger {
public:
  static Logger* Instance();
private:
  Logger(){};

  static Logger* m_pInstance;

};

Logger* Logger::m_pInstance = NULL;

Logger* Logger::Instance()
{
   if (!m_pInstance)  
     m_pInstance = new Logger;

  return m_pInstance;

}


(via http://www.yolinux.com/TUTORIALS/C++Singleton.html)