我是否应该期望单一继承中的上下转换不会调整指针? [英] Should I expect that upcasts and downcasts in single inheritance don't adjust the pointer?
本文介绍了我是否应该期望单一继承中的上下转换不会调整指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有:
class Base {
public:
virtual void Nothing() {}
};
class MiddleDerived : public Base {
virtual void Nothing() {}
};
class Derived : public MiddleDerived {
virtual void Nothing() {}
};
我的代码如下:
Derived* object = new Derived();
Base* base = object; //implicit conversion here
void* derivedVoid = object;
void* baseVoid = base;
我应该期待baseVoid == derivedVoid
吗?
我知道大多数实现都是以这种方式工作的,但是可以保证吗?
I know that most implementations work this way but is it guaranteed?
推荐答案
我认为处理此问题的标准部分为§5.2.9(13)
I think the part of the standard that deals with this is §5.2.9 (13)
(简而言之)声明T *转换为void *然后返回T *应当引用同一对象.
Which states (in a nutshell) that a T* cast to a void* and then back to a T* shall refer to the same object.
但是没有规定Derived
的地址必须与它的Base
的地址相同.
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".
这篇关于我是否应该期望单一继承中的上下转换不会调整指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文