OGRE中的Singleton是这么设计的:
template <typename T> class Singleton
{
private:
/** \brief Explicit private copy constructor. This is a forbidden operation.*/
Singleton(const Singleton<T> &);
/** \brief Private operator= . This is a forbidden operation. */
Singleton& operator=(const Singleton<T> &);
protected:
static T* ms_Singleton;
public:
Singleton( void )
{
assert( !ms_Singleton );
#if defined( _MSC_VER ) && _MSC_VER < 1200 //MS编译器版本低于VC6.0
int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1; //就是这个offset
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; }
};
上面的这句:
#if defined( _MSC_VER ) && _MSC_VER < 1200
int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
ms_Singleton = (T*)((int)this + offset);
#else
困扰我许久,在网上也找了一些资料看了,似懂非懂。
看来要将《深度探索C++对象模型》好好的研读一下了,先记下问题,容我稍后作答^ ^