虚构继承中的析构函数 [英] Destructor in virtual inheritance

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

问题描述

class Base{};
class D1:virtual public Base{};
class D2:virtual public Base{};
class DD:public D1,public D2{};

int main(){
    Base *pBase=new DD;
    delete pBase;
}

这会导致崩溃,但我修改如下:

This leads to crash, but I modify as below:

class Base{
public:
    virtual ~Base(){};
};

class D1:virtual public Base{
public:
    virtual ~D1(){}
};

class D2:virtual public Base{
public:
    virtual ~D2(){}
};

class DD:public D1,public D2{
};

然后,它传递,但是默认析构函数应该是虚拟虚拟函数,不是吗?

Then, it passes, but the default destructor should be the virtual dummy function, isn't it?

推荐答案

这与虚拟继承无关。

通过指向除了最初分配的类型D之外的类型T的指针是未定义行为,除非类型T是D的基类并且具有虚拟析构函数。

Deleting via a pointer to type T other than the originally allocated type D is Undefined Behavior unless the type T is a base class of D and has a virtual destructor.


…如果要删除的对象的静态类型与其
动态类型不同,则静态类型应为要删除的对象的动态类型的基类,
静态类型应具有虚拟析构函数或行为未定义。

… if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

虚拟析构函数用于标识类型D,特别是其大小和析构函数, (你的代码没有)。

The virtual destructor is used to identify the type D, in particular its size and its destructor, and possibly its custom deallocation function (your code doesn't have that).

Re


< / strong>默认析构函数应该是虚拟虚拟函数,不是吗?

the default destructor should be the virtual dummy function, isn't it?

不,不是。

因为C ++设计的一个指导原则是你不支付对于你不使用的,另一个指导原则是让程序员控制,具有表达任何需要的能力(例如为了在内存中的二进制布局的目的)。

Because one guiding principle of the design of C++ is that you don't pay for what you don't use, and another guiding principle is to leave the programmer in control, with the ability to express whatever's needed (e.g. for purposes of binary layout in memory).

只有基类有一个虚拟析构函数,你才能得到默认的虚拟析构函数。

You get a default virtual destructor only if the base class has a virtual destructor.

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

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