刚刚跟朋友讨论单体模式的实现,以下是我为公司写的基类的实现,应该是经过很多项目的考验的,拿出来跟大家探讨下,
/**
* @author konyel lin
* @version 0.1
* @brief Singleton
*/
#include <cassert>
#ifndef EXPORT_H
#define EXPORT_H
#define Export _declspec(dllexport)
#endif
#ifndef _SINGLETON_H__
#define _SINGLETON_H__
template <typename T> class Singleton
{
protected:
static T* ms_Singleton;
public:
Singleton( void )
{
assert( !ms_Singleton );
* @author konyel lin
* @version 0.1
* @brief Singleton
*/
#include <cassert>
#ifndef EXPORT_H
#define EXPORT_H
#define Export _declspec(dllexport)
#endif
#ifndef _SINGLETON_H__
#define _SINGLETON_H__
template <typename T> class Singleton
{
protected:
static T* ms_Singleton;
public:
Singleton( void )
{
assert( !ms_Singleton );
//vc编译器
#if defined( _MSC_VER ) && _MSC_VER < 1200
int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
ms_Singleton = (T*)((int)this + offset);
#else
ms_Singleton = static_cast<T*>( this );
#endif
}
~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; }
};
#endif
#if defined( _MSC_VER ) && _MSC_VER < 1200
int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
ms_Singleton = (T*)((int)this + offset);
#else
ms_Singleton = static_cast<T*>( this );
#endif
}
~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; }
};
#endif