给定一个带有虚函数 f 的基类 B,一个派生类 D 和它自己的 f 实现,这是我的场景:
B& b = *new D; b.f();
D& d = *new D; d.f();
项目符号 1 中的代码是否涉及从 vtable 中获取 f 的地址然后跳转? list 2 中的代码是否涉及任何 vtable 查找?
我知道这些可能依赖于编译器,也许标准不会指定实现细节。在那种情况下,如果了解 GCC 或 CLANG 如何处理这些情况的人提供解释,我将不胜感激。
谢谢。
编辑:请剪切粘贴您的汇编程序输出;我仍然不确定为什么在第二种情况下应该在 vtable 中进行任何查找。
最佳答案
来自维基:
The C++ standards do not mandate exactly how dynamic dispatch must be implemented, but compilers generally use minor variations on the same basic model. Typically, the compiler creates a separate vtable for each class.
编译器将为每个包含virtual
函数的类创建一个 vtable,如 here 所述:
every class that uses virtual functions (or is derived from a class that uses virtual functions) is given it’s own virtual table. This table is simply a static array that the compiler sets up at compile time. A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.
关于c++ - 调用虚函数 : compare base versus derived reference calls?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607182/