|
#ifndef TSINGLETON_TEMPLATE
#define TSINGLETON_TEMPLATE
//////////////////////////////////////////////////////////////////////////////////
// TSingleton template class is used to transform other classes into a singleton.
// Example:
// typedef TSingleton<CSomeClass> STSomeClass;
// STSomeClass::InstPtr STSomeClass::sm_ptr;
// and from then on use:
// CSomeClass* csc = TSingleton<CSomeClass>::Instance();
// or
// CSomeClass* csc = STSomeClass::Instance();
template<class T>
class TSingleton
{
private:
// helper class that holds a pointer to the type
class InstPtr
{
public:
InstPtr() : m_ptr(0) {}
~InstPtr() { delete m_ptr; }
T* Get() { return m_ptr; }
void Set(T* p)
{
if(p!= 0)
{
delete m_ptr;
m_ptr = p;
}
}
private:
T* m_ptr;
};
// Singleton pattern - private constructors and operator=
static InstPtr sm_ptr;
TSingleton();
TSingleton(const TSingleton&);
TSingleton& operator=(const TSingleton&);
public:
// Get instance function
static T* Instance()
{
if(sm_ptr.Get() == 0)
{
sm_ptr.Set(new T());
}
return sm_ptr.Get();
}
};
#endif
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Software designer and programmer.
Programming languages:
MFC, C++, Java , C#, VB and sometimes C and assembly.