这东西可能每个引擎里都有吧, 不管它是宏还是模板.
用宏的人可能觉得模板编译慢, 另外不想多继承
用模板的人可以觉得宏丑陋, 不利于调试
不管哪种方式, 个人觉得这个东西总比全局变量好
这里说说几种常见的情况:
template <class T>
class Singleton
{
public:
static T* GetInstance()
{
static T singleton;
return &singleton;
}
};
template <class T>
class Singleton
{
private:
static T *s_pSingleton;
public:
Singleton()
{
assert(NULL == s_pSingleton);
s_pSingleton = static_cast<T*>(this);
}
~Singleton()
{
assert(NULL != s_pSingleton);
s_pSingleton = NULL;
}
static T* GetInstance()
{
return s_pSingleton;
}
};
template <class T> T* Singleton<T>::s_pSingleton = NULL;
#define ThreadLocal __declspec(thread)
template <class T>
class Singleton
{
private:
ThreadLocal static T *s_pSingleton;
public:
Singleton()
{
assert(NULL == s_pSingleton);
s_pSingleton = static_cast<T*>(this);
}
~Singleton()
{
assert(NULL != s_pSingleton);
s_pSingleton = NULL;
}
static T* GetInstance()
{
return s_pSingleton;
}
};
template <class T> T* Singleton<T>::s_pSingleton = NULL;
class ThreadLocalIndex
{
public:
ThreadLocalIndex()
{
m_tlsIndex = TlsAlloc();
}
~ThreadLocalIndex()
{
TlsFree(m_tlsIndex);
}
operator DWORD() const
{
return m_tlsIndex;
}
private:
DWORD m_tlsIndex;
};
template <class T>
class Singleton
{
private:
static DWORD GetThreadLocalIndex()
{
static ThreadLocalIndex index;
return index;
};
public:
Singleton()
{
assert(NULL == GetInstance());
TlsSetValue(GetThreadLocalIndex(), static_cast<T*>(this));
}
~Singleton()
{
assert(NULL != GetInstance());
TlsSetValue(GetThreadLocalIndex(), NULL);
}
static T* GetInstance()
{
return (T*)TlsGetValue(GetThreadLocalIndex());
}
};