虚函数的Vtable如何工作 [英] How Vtable of Virtual functions work

查看:97
本文介绍了虚函数的Vtable如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在虚拟表中有一个小小的疑问,每当编译器遇到一个类中的虚函数时,它会创建Vtable并将虚函数地址放在那里。它对于继承的其他类发生类似。它是否在每个类中创建一个指向每个Vtable的新指针?如果没有,当创建派生类的新实例并分配给Base PTR时,如何访问Virtual函数?

解决方案

你创建一个包含虚函数的类,或者
从包含虚函数的类派生,编译器
为该类创建一个唯一的VTABLE。



如果
不覆盖基类中声明为虚拟的函数
,编译器将使用
派生类中的基类版本的地址。 / p>

然后将VPTR放入
类中。使用简单的
继承时,每个对象只有一个VPTR。 VPTR必须初始化为指向相应VTABLE的
起始地址。 (这发生在
构造函数中。)
一旦VPTR被初始化为正确的VTABLE,
中的对象会知道它是什么类型。但是这种自我知识是无价值的
,除非它被使用在虚拟函数被调用的点。
当你通过一个基类地址调用一个虚函数时(
情况,当编译器没有所有的信息
需要执行早期绑定),一些特殊的事情发生。
而不是执行一个典型的函数调用,这只是一个
汇编语言调用到一个特定的地址,编译器
生成不同的代码来执行函数调用。


I have a small doubt in Virtual Table, whenever compiler encounters the virtual functions in a class, it creates Vtable and places virtual functions address over there. It happens similarly for other class which inherits. Does it create a new pointer in each class which points to each Vtable? If not how does it access the Virtual function when the new instance of derived class is created and assigned to Base PTR?

解决方案

Each time you create a class that contains virtual functions, or you derive from a class that contains virtual functions, the compiler creates a unique VTABLE for that class.

If you don’t override a function that was declared virtual in the base class, the compiler uses the address of the base-class version in the derived class.

Then it places the VPTR into the class. There is only one VPTR for each object when using simple inheritance . The VPTR must be initialized to point to the starting address of the appropriate VTABLE. (This happens in the constructor.) Once the VPTR is initialized to the proper VTABLE, the object in effect "knows" what type it is. But this self-knowledge is worthless unless it is used at the point a virtual function is called. When you call a virtual function through a base class address (the situation when the compiler doesn’t have all the information necessary to perform early binding), something special happens. Instead of performing a typical function call, which is simply an assembly-language CALL to a particular address, the compiler generates different code to perform the function call.

这篇关于虚函数的Vtable如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆