游戏开发论坛

 找回密码
 立即注册
搜索
查看: 2344|回复: 1

有关OGRE中单件代码的问题

[复制链接]

54

主题

116

帖子

122

积分

注册会员

Rank: 2

积分
122
发表于 2008-8-13 15:55:00 | 显示全部楼层 |阅读模式
OGRE的源代码中有下面的单件代码。有两句看不懂 。

            int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
            ms_Singleton = (T*)((int)this + offset);
貌似是计算内存地址的,小弟基础有点差。请问这两句具体是如何计算的呢?谢谢了

template <typename T> class Singleton
    {
    protected:

        static T* ms_Singleton;

    public:
        Singleton( void )
        {
            assert( !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
            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; }
    };

0

主题

2

帖子

0

积分

新手上路

Rank: 1

积分
0
发表于 2012-3-31 16:09:00 | 显示全部楼层

Re:有关OGRE中单件代码的问题

结合用法来看, 用的时候是从这个单件类派生的:
class MyClass : public Singleton<MyClass> ...
在这里 MyClass 是派生类, Singleton<MyClass> 是基类. 为了方便, 我们用 Derive和 Base 来代替它们, 于是可以得到:
int offset = (int)(Derive*)1 - (int)(Base*)(Derive*)1;
ms_Singleton = (Derive*)((int)this + offset);
其中, 第一句是在计算派生类和基类之间的偏移(在单继承中这通常是 0, 在多继承当中,它和继承的顺序有关, 具体参见 <<深度探索C++对象模型>> 一书).
第二个把基类的指针加上 派生类和基类之间的偏移 后, 就把基类的 this 指针转换成为了派生类的指针了.

所以, 这两句只是在做一个指针的转型, 即 #else 后面那一句  ms_Singleton = static_cast< T* >( this ); 的功能.
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2025-2-28 17:15

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表