class Singleton
{
public:
static Singleton& Instance()
{
if ( !pInstance )
{
if (destroyed_ )
{
OnDeadReference();
}
else
{
Create();
}
}
return * pInstance_;
}
private:
static void Create()
{
static Singleton theInstance;
pInstance_ = & theInstance ;
}
static void OnDeadReference()
{
Create();
new( pInstance_ ) Singleton;
atexit( KillPhoenixSingleton);
destroyed_ = false;
}
virtual ~Singleton()
{
pInstance_ = 0;
destroyed_ = true;
}
void KillPhoenixSingleton()
{
pInstance ->Singleton();
}
static Singleton * pInstance;
static bool destroyed_
Singleton();
Singleton( const Singleton & );
Singleton& operator = ( const Singleton & );
};
实际上编译器会为Instance产生这样的代码:
Singleton& Singleton::Instance()
{
extern void __ConstructSingleton( void* memory );
extern void __DestroySingleton();
static bool __initialized = false;
static char __buffer [ sizeof( Singleton) ];
if( ! __initialized )
{
__ConstructSingleton( __buffer );
atexit( __DestroySingleton );
__initialized = true;
}
return * reinterpret_cast< Singleton * >( __object );
}