gpt4 book ai didi

c++ - 为什么删除一个没有virtual dtor的类如果它继承了一个有virtual dtor的类就可以了

转载 作者:太空狗 更新时间:2023-10-29 19:45:13 35 4
gpt4 key购买 nike

考虑下面的代码

#include <cstdio>
#include <memory>

struct Base1
{
Base1() = default;
virtual ~Base1() = default;
//~Base1() = default;
};

struct Base2 : public Base1
{
Base2()
{
printf("%s:%d:%s\n", __FILE__, __LINE__, __func__);
}
~Base2() // non-virtual destructor
{
printf("%s:%d:%s\n", __FILE__, __LINE__, __func__);
}
};

struct Derive : public Base2
{
Derive()
{
printf("%s:%d:%s\n", __FILE__, __LINE__, __func__);
}
~Derive()
{
printf("%s:%d:%s\n", __FILE__, __LINE__, __func__);
}
};

int main()
{
std::unique_ptr<Base2> d = std::make_unique<Derive>();
return 0;
}

类(class)Base2没有虚拟析构函数,但它继承了 Base1它有一个虚拟析构函数。

代码std::unique_ptr<Base2> d = std::make_unique<Derive>();正在尝试删除 Base2Derive 类型的对象上,我只期待 Base2的 dtor 被调用,但不是 Derive .

但实际上它工作正常:

main.cpp:15:Base2
main.cpp:27:Derive
main.cpp:31:~Derive
main.cpp:19:~Base2

所以看起来只要“真正的”基类(这里是Base1)有虚拟dtor,所有的继承类都不需要有虚拟dtor,是吗?如果是,我在哪里可以找到这方面的相关文件?

最佳答案

是的,如果一个类有一个基类,其 destructor被声明为virtual,它的析构函数也将是virtual;无论是否显式声明它为 virtual

Even though destructors are not inherited, if a base class declares its destructor virtual, the derived destructor always overrides it. This makes it possible to delete dynamically allocated objects of polymorphic type through pointers to base.

class Base {
public:
virtual ~Base() { /* releases Base's resources */ }
};

class Derived : public Base {
~Derived() { /* releases Derived's resources */ }
};

int main()
{
Base* b = new Derived;
delete b; // Makes a virtual function call to Base::~Base()
// since it is virtual, it calls Derived::~Derived() which can
// release resources of the derived class, and then calls
// Base::~Base() following the usual order of destruction
}

来自标准,[class.dtor]/13

(强调我的)

A prospective destructor can be declared virtual ([class.virtual]) or pure virtual ([class.abstract]). If the destructor of a class is virtual and 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.

关于c++ - 为什么删除一个没有virtual dtor的类如果它继承了一个有virtual dtor的类就可以了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58024743/

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