dynamic_cast不适用于非多态类型的原因 [英] The reason why dynamic_cast doesn't work with non-polymorphic types

查看:419
本文介绍了dynamic_cast不适用于非多态类型的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有类B和派生类D:

class B {
    int b;
};


class D : public B {
    int d;
};


D* d = new D();
B* b = dynamic_cast<B*>(d);

上面的方法可以正常工作-这很简单.我们确定b所指向的对象中都具有B类(子)对象.

the above will work fine—it's a simple upcasting. We're sure that whatever b is pointing at has the B class (sub-)object in it.

但是

B* b = new D();
D* d = dynamic_cast<D*>(b);

即使b指向有效的D实例,

也不会编译,因为该基类不是多态的.因此,仅添加一个空的虚拟方法即可解决该问题.

won't compile even though b points to a valid D instance—because the base class is not polymorphic. So adding just one, empty virtual method would solve the problem.

重要的问题是为什么C ++要求源类型是多态的?我找到的唯一解释是,但它仅说明因为这是内部实现的方式"-至少在我的眼睛).设计dynamic_cast的人可能还会想到其他一些原因-那是什么?

The important question is why C++ requires the source type to be polymorphic? The only explanation I've found is this, but it merely states 'because that's how it's implemented internally' - at least in my eyes). People who designed dynamic_cast probably had some other reasons in mind - what were those?

推荐答案

因为如果没有一些类型信息存储在对象中以供运行时使用,则无法实现dynamic_cast.而且,只有两种语言的功能需要有关对象类型的运行时信息:虚函数和dynamic_cast.

Because there is no way to implement dynamic_cast without some type information stored in the object for run-time use. And there are only two features of the language which need a run-time information on the object's type: virtual functions, and dynamic_cast.

如果可以使用dynamic_cast向下转换非多态类型,则编译器必须将运行时类型信息存储在每个类类型中.这将直接违背C ++的只为所用内容付费"的原则,并且会完全破坏与C ++和许多外部接口,硬件等的兼容性.将没有标准布局类类型,基本上.或者,也没有可以完全控制其布局的类类型.

If it was possible to use dynamic_cast to downcast non-polymorphic types, compliers would have to store run-time type information in every class type. This would go directly against the "only pay for what you use" philosophy of C++, and it would utterly break its compatibility with C and many external interfaces, hardware etc. There would be no standard-layout class types, basically. Or, alternatively, no class types where you could have full control of their layout.

这篇关于dynamic_cast不适用于非多态类型的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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