#ifndef __SINGLETON_H #define __SINGLETON_H #include "ScopedPtr.hpp" #include "NonCopyable.hpp" #include "UtilExportable.hpp" #include "Noreturn.hpp" #include #include #define DECLARE_SINGLETON( T ) \ friend class Singleton< T >; \ friend class scopedPtr< T >; #define DEFINE_SINGLETON( T ) \ template class Singleton< T >; template< class T > class Singleton : private noncopyable { public: static UTIL_DLL_VISIBLE T& instance( ) { if( destroyed ) { onDeadReference( ); } if( t == 0 ) { create( ); } return *t; } protected: Singleton( ) { } virtual ~Singleton( ) { destroyed = true; } private: static void create( ) { t.reset( new T ); } static void onDeadReference( ) CRAWLER_NORETURN { throw std::runtime_error( "singleton has already been destroyed!" ); } static scopedPtr t; static bool destroyed; }; template< class T > scopedPtr Singleton::t( 0 ); template< class T > bool Singleton::destroyed( false ); #endif