Created
March 27, 2012 08:14
-
-
Save shihongzhi/2213918 to your computer and use it in GitHub Desktop.
Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
class cSingleton | |
{ | |
static T* ms_Singleton; | |
public: | |
cSingleton( void ) | |
{ | |
assert( !ms_Singleton ); | |
int offset = (int)(T*)1 - (int)(cSingleton <T>*)(T*)1; //这里的offset主要处理多重继承,及虚继承的情况地址的偏移量 | |
ms_Singleton = (T*)((int)this + offset); | |
} | |
~cSingleton( void ) | |
{ assert( ms_Singleton ); ms_Singleton = 0; } | |
static T& GetSingleton( void ) | |
{ assert( ms_Singleton ); return ( *ms_Singleton ); } | |
static T* GetSingletonPtr( void ) | |
{ return ( ms_Singleton ); } | |
}; | |
template <typename T> | |
T* cSingleton<T>::ms_Singleton = 0x0; | |
//要实现单件功能的类必须继承这个类才行的 | |
//class CTeminator : public cSingleton<CTeminator> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment