C++虚函数除了vtable怎么实现? [英] How can C++ virtual functions be implemented except vtable?

查看:36
本文介绍了C++虚函数除了vtable怎么实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
一个关于C++中虚拟机制的问题

在 C++ 中使用 vtable 是实现虚成员函数机制的唯一方法吗?还有哪些其他方式?

Is using vtable the only way to implement virtual member functions mechanism in C++? What other ways exist?

推荐答案

另一个已知的机制是类型调度函数.实际上,您将 vtable 指针替换为 typeid(小枚举).(动态)链接器收集给定虚函数的所有覆盖,并将它们包装在 typeid 字段上的一个大 switch 语句中.

Another known mechanism is type dispatch functions. Effectively, you replace the vtable pointer by a typeid (small enum). The (dyanmic) linker collects all overrides of a given virtual function, and wraps them in one big switch statement on the typeid field.

理论上的理由是,这用大量可预测的跳跃代替了间接跳跃(不可预测的).在选择枚举值方面有一些技巧,switch 语句也可以相当有效(即比 lineair 更好)

The theoretical justifcation is that this replaces an indirect jump (non-predicatble) by lots of predicatable jumps. With some smarts in choosing enum values, the switch statement can be fairly effective too (i.e. better than lineair)

这篇关于C++虚函数除了vtable怎么实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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