Should I expect that upcasts and downcasts in single inheritance don't adjust the pointer?

别来无恙 提交于 2019-12-10 14:49:22

问题


Suppose I have:

class Base {
public:
    virtual void Nothing() {}
};
class MiddleDerived : public Base {
    virtual void Nothing() {}
};
class Derived : public MiddleDerived {
    virtual void Nothing() {}
};

and my code goes like this:

Derived* object = new Derived();
Base* base = object; //implicit conversion here

void* derivedVoid = object;
void* baseVoid = base;

Should I expect that baseVoid == derivedVoid?

I know that most implementations work this way but is it guaranteed?


回答1:


What you "should expect" can be different from what's guaranteed.

A static_cast up or down an inheritance chain can change the address.

The canonical example where this occurs in practice is where a base class is non-polymorphic and a derived class introduces some virtual function, which with many compilers then introduce a vtable pointer at the start of each derived object.




回答2:


I think the part of the standard that deals with this is §5.2.9 (13)

Which states (in a nutshell) that a T* cast to a void* and then back to a T* shall refer to the same object.

However there is no stipulation The address of Derived must be the same as the address of its Base.

So my answer would be, "no - code that expects this equivalency is ill-formed inviting undefined behaviour".



来源:https://stackoverflow.com/questions/34993934/should-i-expect-that-upcasts-and-downcasts-in-single-inheritance-dont-adjust-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!