How can C++ virtual functions be implemented except vtable?(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怎么实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++虚函数除了vtable怎么实现?
基础教程推荐
- 读取名字和身高并显示信息 1970-01-01
- 使用基本数据类型,并输出它们的值,int,floa 1970-01-01
- C++函数调用运算符()重载 1970-01-01
- 使用printf()显示int类型的变量 1970-01-01
- C++ - 指向对象的向量的性能与对象的性能 2022-10-18
- \a序列表示“钟”字符。 1970-01-01
- C++条件编译 1970-01-01
- C++ #define 1970-01-01
- C语言库difftime()函数 1970-01-01
- C++递增指针 1970-01-01