C++:单例模式

来自WHY42

这是CEGUI源码中的单例模式实现模版:

#include <cassert>
template <typename T> class CEGUIEXPORT Singleton
{
protected:
    static
#ifdef __MINGW32__
    CEGUIEXPORT
#endif
    T* ms_Singleton;

public:
    Singleton( void )
    {
        assert( !ms_Singleton );
        ms_Singleton = static_cast<T*>(this);
    }
   ~Singleton( void )
        {  assert( ms_Singleton );  ms_Singleton = 0;  }
    static T& getSingleton( void )
        {  assert( ms_Singleton );  return ( *ms_Singleton );  }
    static T* getSingletonPtr( void )
        {  return ( ms_Singleton );  }

private:
    Singleton& operator=(const Singleton&) { return this; }
    Singleton(const Singleton&) {}
};

下面是它的system类,使用了这个单例模版:

class CEGUIEXPORT System :
    public Singleton<System>{
...
static	System&	getSingleton(void);
static	System*	getSingletonPtr(void);
}

System&	System::getSingleton(void)
{
	return Singleton<System>::getSingleton();
}

System*	System::getSingletonPtr(void)
{
	return Singleton<System>::getSingletonPtr();
}