Hi, im having a little trouble with writing a simple singleton.
My implementation is as follows:
// Singleton.h
#pragma once
template <class T>
class CSingleton
{
public:
static T* CreateInstance(void);
static void DeleteInstance(void);
static T* GetInstancePtr(void);
static T& GetInstanceRef(void);
private:
CSingleton(void);
CSingleton(const CSingleton& rCopy);
CSingleton& operator=(const CSingleton& rCopy);
~CSingleton(void);
static T* m_pT;
};
template <class T>
T* CSingleton<T>::m_pT = NULL;
template <class T>
CSingleton<T>::CSingleton(void)
{
}
template <class T>
CSingleton<T>::~CSingleton(void)
{
}
template <class T>
T* CSingleton<T>::CreateInstance(void)
{
if (m_pT == NULL)
m_pT = new T();
return m_pT;
}
template <class T>
void CSingleton<T>::DeleteInstance(void)
{
if (m_pT != NULL)
{
delete m_pT;
m_pT = NULL;
}
}
template <class T>
T* CSingleton<T>::GetInstancePtr(void)
{
return m_pT;
}
template <class T>
T& CSingleton<T>::GetInstanceRef(void)
{
return *m_pT;
}
But it has lead to problems when trying to make a logging class a singleton:
// Log.h
#pragma once
class CLog : public CSingleton<CLog>
{
public:
CLog(void);
~CLog(void);
};
// Engine.cpp
...
CLog* pLog = CLog::GetInstancePtr();
CLog* pLog2 = new CLog(); // Test to make sure that the user cant make a new object
...
The compiler moans that it cant access the private members __ctor and dtor in the CLogs constructor and destructor. Which obviously makes sense, but if i dont have them as private, the developer is able to call "new CLog()" which means it breaks the singleton rules.
Can anyone give me any pointers where im going wrong?