其他分享
首页 > 其他分享> > c – 虚拟继承中的析构函数

c – 虚拟继承中的析构函数

作者:互联网

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节Destructors [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,那么子类将不具有虚拟析构函数.如果一个类没有基类,编译器生成的析构函数将不是虚拟的.

标签:virtual-destructor,virtual-inheritance,c,destructor,delete-operator
来源: https://codeday.me/bug/20191002/1844050.html