从对超类的引用确定对象标识 [英] Determine object identity from a reference to a superclass

查看:128
本文介绍了从对超类的引用确定对象标识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个函数:

void RegisterSink( ISink & Sink )
void UnregisterSink( ISink & Sink )

其中ISink是一个抽象基类。在内部,我想存储指向std :: set中的sinks指针。当一个接收器未注册时,我只需在我的集合中搜索指针,并删除它。我的问题是,有什么办法,采取参数Sink的地址会产生不同的结果,虽然相同的对象作为参数传递。我知道,指针可以改变时投入某些多继承szenarios,但这种情况怎么办?

Where ISink is an abstract base class. Internally, I would like to store pointers to the sinks in an std::set. When a sink is unregistered, i simply search for the pointer in my set, and remove it. My question is, is there any way, that taking the adress of the parameter Sink would yield different results, although the same object was passed as a parameter. I know, that pointers can change when casting in certain multiple inheritance szenarios, but what about this situation?

提前感谢!

推荐答案

在多重继承的情况下,同一对象的含义有时并不明显。
例如,如果ISink在基类列表中出现两次,并且没有继承virtual,这种情况是可能的:

In case of multiple inheritance the meaning of "same object" sometimes is not obvious. For example, if ISink is present twice in the list of base classes and wasn't inherited with "virtual", such situation is possible:

class A {};
class B:public A {};
class C:public A {};
class D:public B,public C {};
...
void f(A *a);
...
{
    D d;
    f(static_cast<B*>(&d));
    f(static_cast<C*>(&d));
}

在这种情况下,f将获得两个不同的地址。
是否是同一个对象或者可能取决于上下文。
如果你想把它们当作同一个对象,dynamic_casting到void *可能会帮助 - 它强制转换为大多数派生类(当然需要A中的虚拟对象)

In this case f will get two different addresses. Whether is's same object or not probably depends on context. If you want to treat them as the same object, dynamic_casting to void* may help - it castes to most derived class (something virtual in A is needed, of course)

这篇关于从对超类的引用确定对象标识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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