c++ - 虚继承中的析构函数

标签 c++ destructor delete-operator virtual-inheritance virtual-destructor

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;
}

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

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{
};

然后,它通过了,但是默认的析构函数应该是虚拟伪函数,不是吗?

最佳答案

来自 C++11 规范 (ISO/IEC 14882:2011(E)),第 12.4 节析构函数 [class.dtor]:

第 4 小节:

If a class has no user-declared destructor, a destructor is implicitly declared as defaulted (8.4). An implicitly-declared destructor is an inline public member of its class.

第 6 小节:

A destructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used (3.2) to destroy an object of its class type (3.7) or when it is explicitly defaulted after its first declaration.

最后是第 9 小节:

A destructor can be declared virtual (10.3) or pure virtual (10.4); if any objects of that class or any derived class are created in the program, the destructor shall be defined. If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual.

在最后引述中强调我的。

如果基类有虚析构函数,编译器只会生成一个虚析构函数。如果基类没有虚拟析构函数,如第一个示例中的 Base ,则子类将没有虚拟析构函数。如果一个类没有基类,编译器生成的析构函数将不是虚拟的。

关于c++ - 虚继承中的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36760797/

相关文章:

c++ - 相当于 inet_aton 的窗口

c++ - 如何创建一个 vector 并以相反的顺序输出

c++ - 为什么在 C++ 中允许删除空指针

c++ - 用 C++ 类模拟指针(包括删除)

c++ - 将 SDL 用于 Web 应用程序

c++ - MsBuild 并行编译和构建依赖项

C++ 禁止自动初始化和销毁

C++ 太多的析构函数调用了这么少的对象

c++ - 析构函数调用删除函数时程序崩溃

c++ - 智能指针如何在 delete 和 delete[] 之间进行选择?