关于int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;

来源:互联网 发布:少年手指虎淘宝 编辑:程序博客网 时间:2024/05/22 15:20

请看代码:

template <typename T> class Singleton

{

protected:
      static T* ms_Singleton;
public:
       Singleton( void )
       {
            assert( !ms_Singleton );
            int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
            ms_Singleton = (T*)((int)this + offset);
       }
       ~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; }

};


对代码:int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;ms_Singleton = (T*)((int)this + offset);的解释:所有重要工作在Singleton构造函数中完成,它计算出派生类实例的相对位置,并将结果保存在指针ms_Singleton中。派生类可能不仅仅从Singleton派生,这种情况下MyClass的this指针可能与Singleton的this指针不同。这种解决方法假设一个不存在的对象在内存的0x1位置上,将此对象强制转换为两种类型,并获得偏移量的差值。这个差值可以有效地作为Singleton<MyClass>和他派生类MyClass的距离,可用于计算ms_Singleton指针。

参考《游戏编程精粹1》

0 0