21. 더 나은 방식
class CTextureMgr
{
static CTextureMgr* m_Instance;
public:
CTextureMgr() {m_Instance = this;}
~CTextureMgr() {m_Instance = NULL;}
static CTextureMgr& GetInstance() {return *m_Instance;}
}
// 사용
CTextureMgr::GetInstance().Method();
하지만, 모든 싱글톤 클래스에 추가 코드가 들어가야 한다.
22. 좀더 나은 방식
template<typename T>
class ISingleTon
{
static T* m_instance;
public:
ISingleTon()
{
int offset = (int)(T*)1 - (int)(ISingleTon<T>*)(T*)1;
m_instance = (T*)((int)this + offset);
}
~ISingleTon() {m_instance = NULL;}
static T& GetSingleton() {return *m_instance;}
}
템플릿을 상속 받아 하위 클래스에서 자동으로 싱글톤이 생성되게 한다.
다중 상속 구조가 되는 경우가 있기 때문에 Offset을 계산해서 할당한다.