Singleton Class (C++)
-
class CSingleton
{
public:
static CSingleton* GetInstance();private:
void CSingleton();
CSingleton ~CSingleton();static CSingleton* m_pInstance;
};In the cpp file:
CSingleton* CSingleton::m_pInstance = NULL;
// Constructor + Destructor
.....CSingleton* CSingleton::GetInstance()
{
if (!m_pInstance)
m_pInstance = new CSingleton;
return m_pInstance;
}
Cédric Moonen Software developer
Charting control -
-
-
class CSingleton
{
public:
static CSingleton* GetInstance();private:
void CSingleton();
CSingleton ~CSingleton();static CSingleton* m_pInstance;
};In the cpp file:
CSingleton* CSingleton::m_pInstance = NULL;
// Constructor + Destructor
.....CSingleton* CSingleton::GetInstance()
{
if (!m_pInstance)
m_pInstance = new CSingleton;
return m_pInstance;
}
Cédric Moonen Software developer
Charting controlA simpler way: -------------- // Console.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include using namespace std; class Single { public: static Single& GetInstance() { static Single s; return s; } void Method() const { cout << "Method called : this = 0x" << hex << this << endl; } private: Single() { cout << "Instance created!" << endl; }; }; int main(int argc, char* argv[]) { Single::GetInstance().Method(); Single::GetInstance().Method(); Single::GetInstance().Method(); return 0; } -------------- This technique leverages the langauges rules: A static member is created the first time it's encountered. This way we don't need the "new" or the "if" or to remember to "delete" it. Steve
-
A simpler way: -------------- // Console.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include using namespace std; class Single { public: static Single& GetInstance() { static Single s; return s; } void Method() const { cout << "Method called : this = 0x" << hex << this << endl; } private: Single() { cout << "Instance created!" << endl; }; }; int main(int argc, char* argv[]) { Single::GetInstance().Method(); Single::GetInstance().Method(); Single::GetInstance().Method(); return 0; } -------------- This technique leverages the langauges rules: A static member is created the first time it's encountered. This way we don't need the "new" or the "if" or to remember to "delete" it. Steve
Yes, that another way of doing it. Both techniques have their pro and cons. I remember having read an article that was discussing several singleton implementations but I don't remember the link. Yours is great when it has to be used 'alone' because as you said you don't have to worry about releasing the instance. But in some cases, this can lead to problems: if you have a singleton that is member of another singleton, then you get into trouble because you have no control over the timings of the destruction of the instances. In such case, you need to control yourself the scope of the instances.
Cédric Moonen Software developer
Charting control