gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:54:02 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com