关于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
- int offset = (int)(t*)1 - (int)(singleton *)(t*)1
- int offset = (int)(t*)1 - (int)(singleton *)(t*)1
- 关于int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
- 关于int &const t和 int const& t
- int & const t和 int const& t
- System.Nullable<T> int?
- C++测试小记(1)——array1d(int n, T val=T()) vs array1d(int n, T val=T(0))
- 不能将参数 1 从“int &(__thiscall RBTree<T>::* )(RBTreeNode<T> *)”转换为“int &(__cdecl *)(RBTreeNode<T> *)”
- template<typename T,int n>
- template <class T> T * funcNew(T x,int n)
- ViewGroup.layout(int l, int t, int r, int b)四个输入参数的含义
- ViewGroup.layout(int l, int t, int r, int b)四个输入参数的含意
- ViewGroup.layout(int l, int t, int r, int b)四个输入参数的含意
- int *bsearch(int *t, int n, int x); 二分查找完全实现
- View中layout(int l, int t, int r, int b)方法的理解
- 自定义viewGroup时候.layout(int l, int t, int r, int b)方法说明
- 自定义viewGroup时候.layout(int l, int t, int r, int b)方法说明
- System.arraycopy(T[] src,T srcBegin,T []des,T desBegin,int Length)
- 最大流问题
- ceph存储 FC HBA、iSCSI HBA、以太网卡3者区别
- 在TOMCAT中部署war
- Eclipse将引用了第三方jar包的Java项目打包成jar文件的两种方法
- JIRA、Jira client和jqGrid实践
- 关于int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
- java web项目 权限管理
- 数据库自学笔记
- MySQL填充字符串的函数LPAD(s1,len,s2)和RPAD(s1,len,s2)
- 深复制与浅复制
- C++ Primer第五版刷刷总结之第一章例程
- c/c++ (疑1)数组和指针
- MVC+LINQ+EF实战(.NET平台)
- rails项目编写中的一些小技巧小心得