检测两个接口指针是同一个对象 [英] Detecting two interface pointers are the same object

查看:78
本文介绍了检测两个接口指针是同一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有多个接口继承的类层次结构

例如

I''ve got a class hierarchy of multiple interface inheritance

e.g.

IBase
IInterface1: public IBase
IInterface2: public IBase

CClass: public IInterface1, IInterface2


(所有这些接口都是纯虚拟的)

现在,如果我有一个接受两种类型对象的函数:


(all these interfaces are pure virtual)

Now, if I have a function that takes objects of both types:

void MyFunc( IInterface1* pObj1, IInterface2* pObj2 );


如何检测pObj1和pObj2是否为同一对象?由于多重继承,我不能简单地转换为IBase *.

到目前为止,我发现的最佳答案是在IBase中具有GetUID()方法,并使每个对象在创建时生成一个UID.有更好的解决方案吗?

[更新] 简单地比较指针是行不通的-即使将其转换为基数,因为pObj1具有Interface1的IBase实现,而pObj2具有Interface2的IBase实现(由于到c ++ vtables的工作方式)


how can I detect if pObj1 and pObj2 are the same object? I can''t simply cast down to IBase*, because of the multiple inheritance.

So far, the best answer I''ve found is to have a GetUID() method in IBase, and make each object generate a UID at creation time. Is there a better solution?

[update] Simply comparing the pointers won''t work - even if cast down to base, since pObj1 has Interface1''s implementation of IBase, and pObj2 has Interface2''s implementation of IBase (due to the way c++ vtables work)

推荐答案

比较指针不起作用,因为两个基数具有不同的偏移量,并且强制转换为CClass 可能不是您所需要的意思是(可能不是系统中唯一具有此属性"的唯一类).

正确的方法是
Comparing pointers doesn''t work because the two bases have different offset, and casting to CClass may not be what you mean (may be it is not the only class in your system actually having this "property").

The proper way is
dynamic_cast<void*>(pobj1) == dynamic_cast<void*>(pobj2) 

根据定义,将比较对象最外部的地址,而不管运行时类型是什么,也不管比较的基数是什么.

that, by definition, will compare the addresses of the most external part of the objects whatever the runtime type is and whatever the compared bases are.


这篇关于检测两个接口指针是同一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆