# 虚函数

**虚函数**是一种非静态成员函数，其调用在运行时根据对象的动态类型来解析，而非在编译时根据用于调用它的指针或引用的静态类型来解析。用C++标准的话说，虚函数调用的解释取决于被调用对象的类型（动态类型），而非虚调用仅取决于指代该对象的指针或引用的类型（静态类型）<sup>[1](https://eel.is/c++draft/class.virtual)</sup>。声明或继承了虚函数的类称为*多态类*，虚函数支持动态绑定和面向对象编程<sup>[1](https://eel.is/c++draft/class.virtual)</sup>。

| 关键事实 | 详情 |
|---|---|
| 使函数成为虚函数的条件 | 首次声明时使用关键字`virtual`，或重写基类的虚函数；虚性通过重写被继承<sup>[1](https://eel.is/c++draft/class.virtual)</sup> |
| `virtual`可出现的位置 | 仅可出现在非静态成员函数的首次声明中；静态函数和非成员函数不能是虚函数<sup>[2](https://en.cppreference.com/cpp/language/virtual)</sup> |
| 运行时机制 | 常见实现在多态对象中使用隐藏的vptr指向虚表；虚调用可加载vptr，从表槽中加载函数地址，然后间接跳转<sup>[3](https://jasper-aa64.github.io/ref/cpp-syntax/)</sup> |
| 内存开销 | FAQ的粗略估计：每个需要动态绑定的对象多一个指针，每个虚方法多一个指针<sup>[4](https://isocpp.org/wiki/faq/virtual-functions)</sup><sup> • </sup><sup>[5](https://cppcheatsheet.com/notes/cpp/cpp_polymorphism.html)</sup> |
| 实测程序开销 | 调度代码中位数占执行时间的5.2%、指令数的3.7%；“全虚”版本中时间占比达13.7%<sup>[6](https://dl.acm.org/doi/10.1145/236338.236369)</sup> |
| 析构函数规则 | 通常规则是：通过基类指针删除派生类对象而基类析构函数非虚，属于未定义行为；若类有任何虚函数，应将析构函数设为虚函数<sup>[2](https://en.cppreference.com/cpp/language/virtual)</sup><sup> • </sup><sup>[4](https://isocpp.org/wiki/faq/virtual-functions)</sup> |
| C++23变更 | 具有显式对象参数（“推导this”）的成员函数不能是虚函数；2024年提案（P3469R0）拟移除该限制<sup>[7](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0847r6.html)</sup><sup> • </sup><sup>[8](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p3469r0.pdf)</sup> |

## 使函数成为虚函数的条件

非静态成员函数在以下情况被视为虚函数：在其首次声明中使用了关键字`virtual`，或者它重写了基类中本身已声明为虚的成员函数。<sup>[1](https://eel.is/c++draft/class.virtual)</sup> `virtual`说明符只能出现在非静态成员函数的首次声明中；静态成员函数和非成员函数不能是虚函数<sup>[2](https://en.cppreference.com/cpp/language/virtual)</sup>。一旦函数在基类中成为虚函数，派生类中的每次重写都是虚函数，无需重复关键字。Google的C++风格指南要求用`override`或`final`中恰好一个来标注重写，并禁止在声明重写时使用`virtual`<sup>[9](https://google.github.io/styleguide/cppguide)</sup>。

当动态类型不可能发挥作用时，调度在静态阶段解析。当使用限定名查找选择函数时，即函数名出现在作用域解析运算符`::`右侧时，虚调用被抑制<sup>[2](https://en.cppreference.com/cpp/language/virtual)</sup>。每个虚函数都有一个*最终重写者*，即虚调用时实际执行的派生类版本<sup>[2](https://en.cppreference.com/cpp/language/virtual)</sup>。

## 虚调度的运作方式

C++标准不规定实现方式，但主流编译器使用**虚表**机制。在Itanium C++ ABI下，虚表是一种信息结构，服务于三个目的：调度虚函数、到达虚基类子对象、为运行时类型识别（RTTI）提供数据；当一个类作为基类时，它可以拥有多个虚表。<sup>[10](https://itanium-cxx-abi.github.io/cxx-abi/abi.html)</sup>

在常见实现中，多态对象携带一个隐藏指针——**vptr**，指向虚表。在[Microsoft Visual C++](https://www.edgepedia.org/zh/microsoft-visual-c)中，隐藏的vfptr被放置在类布局的起始处；诸如`q->pvf()`的调用会获取对象的vfptr，它指向类的vftable，并调用相应条目<sup>[11](https://openrce.org/articles/files/jangrayhood.pdf)</sup><sup> • </sup><sup>[3](https://jasper-aa64.github.io/ref/cpp-syntax/)</sup>。因此编译后的代码执行一次虚调用的过程为：加载vptr，加载表槽，跳转到所加载的地址<sup>[3](https://jasper-aa64.github.io/ref/cpp-syntax/)</sup>。C++ FAQ将其计为比直接调用多两次读取：一次获取v指针的值，第二次获取方法的地址，并指出开销不随继承深度增长：十层继承仍然花费相同的读取-读取-调用序列<sup>[4](https://isocpp.org/wiki/faq/virtual-functions)</sup>。

虚表条目并不总是普通的函数地址。每个这样的指针要么直接指向类的某个虚函数，要么指向一个次级入口点，后者先进行某些调整——多继承指针调整所需——然后再移交控制权；在64位Itanium共享库构建中，每个虚函数指针条目是一对64位组件。<sup>[10](https://itanium-cxx-abi.github.io/cxx-abi/abi.html)</sup>

## 纯虚函数、抽象类和析构函数

用`= 0`声明的函数是**纯虚函数**；声明它的类是抽象类，不能实例化<sup>[5](https://cppcheatsheet.com/notes/cpp/cpp_polymorphism.html)</sup>。为降低**对象切片**的风险——即按值将派生对象赋给基类时只复制基类子对象而丢弃派生状态和行为——Google的风格指南建议限制具体基类的使用，包括将构造函数或析构函数设为受保护，或为这些类提供一个或多个纯虚成员函数，并倾向于避免从具体类派生<sup>[9](https://google.github.io/styleguide/cppguide)</sup>。

**析构函数。** 当基类缺少虚析构函数时，通过基类指针销毁派生类对象会产生未定义行为<sup>[2](https://en.cppreference.com/cpp/language/virtual)</sup>；实践中只有基类析构函数运行，派生部分泄漏<sup>[5](https://cppcheatsheet.com/notes/cpp/cpp_polymorphism.html)</sup>。FAQ的经验法则是：如果你的类有任何`virtual`函数，就将析构函数设为`virtual`<sup>[4](https://isocpp.org/wiki/faq/virtual-functions)</sup>。

**构造与析构。** 在构造或析构期间，“更派生的类不存在”：虚调用解析到构造函数或析构函数所在类中的最终重写者，而非更派生类中重写它的版本<sup>[2](https://en.cppreference.com/cpp/language/virtual)</sup><sup> • </sup><sup>[12](https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP50-CPP.+Do+not+invoke+virtual+functions+from+constructors+or+destructors)</sup>。CERT规则OOP50-CPP解释了原因：派生类尚未有机会初始化其资源，该情况下某些显式成员访问具有未定义行为<sup>[12](https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP50-CPP.+Do+not+invoke+virtual+functions+from+constructors+or+destructors)</sup>。

## 语言比较：C++与Rust

C++和Rust将调度机制放置在不同位置。在C++中，vptr位于对象内部，引用是薄指针；在Rust中，`&dyn Trait`是双机器字的胖指针（64位上为16字节），一个指针指向数据，一个指针指向虚表，因此表在对象外部<sup>[13](https://cppcheatsheet.com/notes/rust/rust_polymorphism.html)</sup>。Rust将静态调度设为默认，通过泛型和`impl Trait`实现，零开销且可内联，代价是二进制文件更大；动态调度通过`dyn Trait`选择启用，携带间接调用开销但二进制文件更小<sup>[13](https://cppcheatsheet.com/notes/rust/rust_polymorphism.html)</sup>。Rust不需要虚析构函数，因为`Box<dyn Trait>`通过`Drop`处理清理<sup>[13](https://cppcheatsheet.com/notes/rust/rust_polymorphism.html)</sup>。对于通过基类指针删除派生类对象的普通操作，通常需要基类具有虚析构函数才能保证行为有定义<sup>[2](https://en.cppreference.com/cpp/language/virtual)</sup>。

## 性能与内存开销

**时间花在哪里。** 虚调用是一种间接分支，硬件通常直到流水线很晚的阶段才知道其目的地<sup>[14](https://johnnysswlab.com/the-true-price-of-virtual-functions-in-c/)</sup>。当调用点的对象类型随机混合时，间接分支预测错误频繁发生，每次约15到20个周期；当类型遵循某种模式时，预测器很少出错<sup>[3](https://jasper-aa64.github.io/ref/cpp-syntax/)</sup>。虚调用还会阻止内联和跨调用优化，这往往是更大的开销<sup>[3](https://jasper-aa64.github.io/ref/cpp-syntax/)</sup>。

**程序级测量。** 一项对实测C++程序的研究发现，这些程序用于调度代码的时间占比中位数为5.2%，指令占比中位数为3.7%；对于程序的“全虚”版本，中位数开销升至时间的13.7%（指令的13%）<sup>[6](https://dl.acm.org/doi/10.1145/236338.236369)</sup>。在同一研究中，在实现虚函数表时采用基于thunk的变体，与标准版本相比将开销中位数降低了21%。<sup>[6](https://dl.acm.org/doi/10.1145/236338.236369)</sup>

**函数大小很重要。** 在一项基准测试中，通过虚调度调用一个短小快速的函数慢了18%（153毫秒对126毫秒），而对于长而慢的函数，差异不到1%<sup>[14](https://johnnysswlab.com/the-true-price-of-virtual-functions-in-c/)</sup>。

**内存。** 在常见实现中，多态对象通常有一个指针的存储用于vptr（64位上通常为8字节），而同一类型的所有实例共享一个虚表<sup>[5](https://cppcheatsheet.com/notes/cpp/cpp_polymorphism.html)</sup><sup> • </sup><sup>[14](https://johnnysswlab.com/the-true-price-of-virtual-functions-in-c/)</sup>。FAQ给出的粗略空间开销估计是：每个需要动态绑定的对象多一个指针，加上每个虚方法多一个指针<sup>[4](https://isocpp.org/wiki/faq/virtual-functions)</sup>。由于虚表布局是二进制接口的一部分，ABI规范管辖条目格式，包括64位Itanium共享库构建中使用的成对64位组件<sup>[10](https://itanium-cxx-abi.github.io/cxx-abi/abi.html)</sup>。

**去虚化。** 当动态类型可证明时，编译器将虚调用替换为直接调用或内联调用：可见的最派生类型、`final`类或重写、局部对象，或链接时优化下的单一实现<sup>[3](https://jasper-aa64.github.io/ref/cpp-syntax/)</sup><sup> • </sup><sup>[5](https://cppcheatsheet.com/notes/cpp/cpp_polymorphism.html)</sup>。带软件守卫检查的去虚化有其自身开销：它通过将单条间接分支指令转换为多条守卫测试指令和直接调用来增加静态代码大小，并且可能将一次可能预测错误的间接调用替换为多次条件分支预测错误<sup>[15](https://safari.ethz.ch/architecture/fall2017/lib/exe/fetch.php?media=vpc_prediction_reducing_the_cost_of_indirect_branches_via_hardware-based_dynamic_devirtualization.pdf)</sup>。

## 数据一览

| 数量 | 值 | 来源 |
|---|---|---|
| 调度占执行时间的比例（实测程序） | 中位数5.2%（全虚版本13.7%） | <sup>[6](https://dl.acm.org/doi/10.1145/236338.236369)</sup> |
| 每次调用微基准开销 | 虚调用2.90纳秒，直接调用1.48纳秒（+1.42纳秒） | <sup>[16](https://github.com/Shubhankar-Gambhir/cpp-dispatch-benchmark)</sup> |
| 间接分支预测错误 | 随机类型混合下约15–20个周期 | <sup>[3](https://jasper-aa64.github.io/ref/cpp-syntax/)</sup> |
| 短小快速被调函数的减速 | 18%（153毫秒对126毫秒）；长被调函数不到1% | <sup>[14](https://johnnysswlab.com/the-true-price-of-virtual-functions-in-c/)</sup> |
| 每对象vptr | 一个指针，64位上通常8字节 | <sup>[5](https://cppcheatsheet.com/notes/cpp/cpp_polymorphism.html)</sup> |
| 一项基准中的文本段大小 | 虚调度6,776字节，函数指针4,727字节（+43%） | <sup>[16](https://github.com/Shubhankar-Gambhir/cpp-dispatch-benchmark)</sup> |

微基准和程序级数据与其说相互矛盾，不如说处于不同尺度：约1.4纳秒的固定每次调用惩罚仅在被调函数短小时占主导，而在整个程序中，调度占比中位数为执行时间的5.2%<sup>[16](https://github.com/Shubhankar-Gambhir/cpp-dispatch-benchmark)</sup><sup> • </sup><sup>[6](https://dl.acm.org/doi/10.1145/236338.236369)</sup>。

## 虚调度的替代方案

一项比较各机制的微基准测量了：直接调用1.48纳秒，虚调度2.90纳秒，函数指针2.43纳秒，解耦CRTP 2.42纳秒，`std::variant`配合`std::visit` 3.71纳秒<sup>[16](https://github.com/Shubhankar-Gambhir/cpp-dispatch-benchmark)</sup>。CRTP（[奇异递归模板模式](https://www.edgepedia.org/zh/curiously-recurring-template-pattern)）实现静态调度：通过CRTP调用比虚调度更快，更重要的是允许函数内联和其他优化<sup>[17](https://eli.thegreenplace.net/2013/12/05/the-cost-of-dynamic-virtual-calls-vs-static-crtp-dispatch-in-c)</sup>。

选择取决于类型集合。虚函数适合仅在运行时已知的开放类型集，如插件或从配置读取的类型；`std::variant`加`std::visit`适合固定类型集；模板或CRTP适合编译时已知的类型。在热路径上，保持一个调用点的类型有模式，或按类型批处理，可减少预测错误<sup>[3](https://jasper-aa64.github.io/ref/cpp-syntax/)</sup>。

## 近期发展

C++23增加了**“推导this”**（P0847），该特性提供了一种指定非静态成员函数的新方式，其中对象作为显式第一参数传递而非隐式传递；对象参数用前缀关键字`this`表示，并由普通函数模板推导规则推导<sup>[7](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0847r6.html)</sup><sup> • </sup><sup>[18](https://devblogs.microsoft.com/cppblog/cpp23-deducing-this/)</sup>。具有显式对象参数的成员函数不能是`static`或`virtual`，也不能有cv限定符或引用限定符；该论文明确为未来允许它们成为虚函数的扩展留有余地<sup>[7](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0847r6.html)</sup>。cppreference记录了同样的限制：具有显式对象参数的成员函数不能是静态的或虚的<sup>[19](https://en.cppreference.com/cpp/language/member_functions)</sup>。

2024年的一项提案P3469R0拟移除该限制，指出显式对象成员函数是唯一不能为虚的非静态成员函数，并展示了允许虚性如何能简化克隆和访问者模式等常见用例<sup>[8](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p3469r0.pdf)</sup>。

## References

1. [ISO C++ Working Draft, [class.virtual]](https://eel.is/c++draft/class.virtual)
2. [virtual function specifier, cppreference.com](https://en.cppreference.com/cpp/language/virtual)
3. [C++ Syntax: What It Compiles To](https://jasper-aa64.github.io/ref/cpp-syntax/)
4. [Standard C++ FAQ: Virtual Functions, Standard C++ Foundation](https://isocpp.org/wiki/faq/virtual-functions)
5. [Polymorphism & Inheritance, cppcheatsheet (C++)](https://cppcheatsheet.com/notes/cpp/cpp_polymorphism.html)
6. [The direct cost of virtual function calls in C++, ACM SIGPLAN Notices](https://dl.acm.org/doi/10.1145/236338.236369)
7. [P0847R6: Deducing this, ISO C++ standards paper](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0847r6.html)
8. [P3469R0: Virtual deducing this, ISO C++ standards paper (2024)](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p3469r0.pdf)
9. [Google C++ Style Guide](https://google.github.io/styleguide/cppguide)
10. [Itanium C++ ABI](https://itanium-cxx-abi.github.io/cxx-abi/abi.html)
11. [C++: Under the Hood, Jan Gray](https://openrce.org/articles/files/jangrayhood.pdf)
12. [OOP50-CPP: Do not invoke virtual functions from constructors or destructors, SEI CERT C++ Coding Standard](https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP50-CPP.+Do+not+invoke+virtual+functions+from+constructors+or+destructors)
13. [Polymorphism, cppcheatsheet (Rust)](https://cppcheatsheet.com/notes/rust/rust_polymorphism.html)
14. [The true price of virtual functions in C++](https://johnnysswlab.com/the-true-price-of-virtual-functions-in-c/)
15. [VPC Prediction: Reducing the Cost of Indirect Branches via Hardware-Based Dynamic Devirtualization, ETH Zürich](https://safari.ethz.ch/architecture/fall2017/lib/exe/fetch.php?media=vpc_prediction_reducing_the_cost_of_indirect_branches_via_hardware-based_dynamic_devirtualization.pdf)
16. [cpp-dispatch-benchmark, GitHub](https://github.com/Shubhankar-Gambhir/cpp-dispatch-benchmark)
17. [The cost of dynamic (virtual calls) vs. static (CRTP) dispatch in C++](https://eli.thegreenplace.net/2013/12/05/the-cost-of-dynamic-virtual-calls-vs-static-crtp-dispatch-in-c)
18. [C++23's Deducing this, Microsoft C++ Team Blog](https://devblogs.microsoft.com/cppblog/cpp23-deducing-this/)
19. [Non-static member functions, cppreference.com](https://en.cppreference.com/cpp/language/member_functions)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Sep 30, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Programming languages › Programming language concepts

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/virtual-function

English original: https://www.edgepedia.org/virtual-function
