c++ - 调用虚函数 : compare base versus derived reference calls?

标签 c++ gcc polymorphism

给定一个带有虚函数 f 的基类 B,一个派生类 D 和它自己的 f 实现,这是我的场景:

  1. B& b = *new D; b.f();
  2. 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/

相关文章:

c++ - 在嵌套模板中使用类成员指针会导致 GCC 错误 "mismatched types Child and Base"

c++ - 将类型存储为变量?对于模板类?

c++ - 创建类的可变包装器

c++ - Progmem 中的数组下标错误?

c++ - 通过指向虚基类的指针访问模板类的模板成员函数?

c# - 在 C# 中,从构造函数调用虚方法是否安全?

Java继承: How to remove items from an ArrayList depending on a property which is not owned by all of the items?

c++ - GCC:使用 -Werror 但将特定错误降级为警告(在命令行中)

C++函数调用汇编模块

c++ - gcc 3.3.3 支持预编译头文件吗?