C ++虚拟析构函数虚拟表 [英] C++ virtual destructor & vtable

查看:92
本文介绍了C ++虚拟析构函数虚拟表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对虚拟析构函数和vtable有一些特定的问题.

I have some specific questions on virtual destructors and vtable.

假设我有以下代码:

class Base
{
public:

    virtual ~Base();

};

class Child : public Base
{
public:

    ~Child();
};

问题:

  1. vtable存储在哪里?它是否始终在基类中,而所有子类仅保留指向它的指针?
  2. 添加虚拟方法只会使sizeof(class)增加8个字节,对吗? (假设是64位系统)如果基类存储表,该如何处理?
  3. 通过new运算符创建Child类型的实例,然后删除...是否将调用Base析构函数? (我之所以问是因为Child类的析构函数不是虚拟的……是否意味着它仅影响Child的子类?).

推荐答案

以下说明假定编译器使用的虚拟调度实现基于虚拟表.

The explanation below assumes that virtual dispatch implementation used by the compiler is based on virtual tables.

  1. 每个带有虚方法(声明或继承)的类都有自己的虚表.如果子类在基类中覆盖了虚拟成员函数,则将指向该覆盖函数的指针放置在类的vtable中;否则,它将保留该类的指针.否则,将保留指向基类实现的指针.

  1. Each class with virtual methods (declared or inherited) has its own virtual table. If a subclass overrides a virtual member function in the base, a pointer to the overriding function is placed in the class's vtable; otherwise, a pointer to base class implementation is kept in place.

添加第一个虚函数会通过vtable指针的大小增加类 instance 的大小.第一个虚拟函数之后的虚函数不会增加实例的大小.

Adding the first virtual function increases the size of the class instance by the size of vtable pointer. Virtual functions after the first one do not add to the size of the instance.

由于~Base是虚拟的,因此即使省略了virtual关键字,~Child也是虚拟的.如果有覆盖,则virtual关键字是可选的.

Since ~Base is virtual, the ~Child is virtual as well, even though virtual keyword is omitted. In case of an override, virtual keyword is optional.

这篇关于C ++虚拟析构函数虚拟表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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