没有RTTI,但仍然是虚拟方法 [英] No RTTI but still virtual methods

查看:113
本文介绍了没有RTTI,但仍然是虚拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++代码,从而禁用dynamic_cast.但是,仍然需要根据目标的运行时类型调度虚拟(多态)方法.难道不是暗示类型信息仍然存在,并且dynamic_cast应该能够一直工作吗?

C++ code can be compiled with run-time type information disabled, which disables dynamic_cast. But, virtual (polymorphic) methods still need to be dispatched based on the run-time type of the target. Doesn't that imply the type information is present anyway, and dynamic_cast should be able to always work?

推荐答案

禁用RTTI会杀死dynamic_casttypeid,但对虚拟功能没有影响.虚函数是通过具有任何虚函数的类的"vtable"调度的.如果您想避免使用vtable,那么就不能使用虚函数.

Disabling RTTI kills dynamic_cast and typeid but has no impact on virtual functions. Virtual functions are dispatched via the "vtable" of classes which have any virtual functions; if you want to avoid having a vtable you can simply not have virtual functions.

很多C ++代码在没有dynamic_cast的情况下也可以工作,几乎所有的代码在没有typeid的情况下都可以工作,但是没有任何虚函数(或者更重要的是,他们期望的功能)的相对较少的C ++应用程序也可以生存.被虚拟变成非虚拟).

Lots of C++ code in the wild can work without dynamic_cast and almost all of it can work without typeid, but relatively few C++ applications would survive without any virtual functions (or more to the point, functions they expected to be virtual becoming non-virtual).

虚拟表(vtable)只是针对所有虚拟功能的按类型查找表的按实例的指针.您只需为使用的东西付费(Bjarne喜欢这种哲学,最初是抵制RTTI).另一方面,使用完整的RTTI,您最终会得到带有大量精心设计的字符串和其他信息的库和可执行文件,这些信息用来描述每种类型的名称以及其他诸如类型之间的层次关系之类的信息.

A virtual table (vtable) is just a per-instance pointer to a per-type lookup table for all virtual functions. You only pay for what you use (Bjarne loves this philosophy, and initially resisted RTTI). With full RTTI on the other hand, you end up with your libraries and executables having quite a lot of elaborate strings and other information baked in to describe the name of each type and perhaps other things like the hierarchical relations between types.

我已经看到禁用RTTI的生产系统将可执行文件的大小缩小了50%.大多数情况是由于大量使用模板的C ++程序中出现大量字符串名称所致.

I have seen production systems where disabling RTTI shrunk the size of executables by 50%. Most of this was due to the massive string names that end up in some C++ programs which use templates heavily.

这篇关于没有RTTI,但仍然是虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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