How a Traditional Singleton Class Works
As the name indicates, the traditional Singleton class allows exactly one instance of the class to be created. The class ensures this by assuming the responsibility to regulate the creation of its objects. The class makes its constructor private, disallowing the direct creation of its objects. In addition, the class defines a static member function that must be called to get an instance of the class. The class also has a static member that stores the pointer to the sole instance of the class. A sample class is shown below:
class Singleton { public: static Singleton* GetObject(); protected: Singleton(); private: static Singleton *m_Instance; }
The only way to get access to an object of the class is to call the static member function GetObject. When called, GetObject first checks if an instance of the class exists, by checking if m_Instance is NULL. If m_Instance is NULL, then this function creates the first and only instance of the class Singleton, assigns it to m_Instance, and returns it. Subsequent calls to GetObject just return the value stored in m_Instance, ensuring that only one instance of the class is ever created.