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怎么实现?
基础教程推荐
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- C语言3个整数的数组 1970-01-01
- C语言数组 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- 总计将在节日礼物上花多少钱 1970-01-01
- C++多态 1970-01-01
- 用指数格式表示浮点数 1970-01-01
- 对 STL 容器的安全并行只读访问 2022-10-25
