c++ - 在具有虚拟析构函数的基类的子类中不指定析构函数是否安全?

标签 c++ inheritance

考虑一个简单的接口(interface)/实现设计:

class Base
{
public:

    virtual ~Base()
    {
        // Virtual empty destructor
    }
};

class Derived : public Base
{
public:

    virtual ~Derived()
    {
        // Lots of clean up code here
        // ...
    }
};

通过这种设计,我了解到以下代码是安全有效的:

Base* base = new Derived();
delete base; // Both Base::~Base and Derived::~Derived get called

但是,想象一下如果有一个新类:

class DerivedEx : public Derived
{
public:

    // No destructor here, relying on default destructor generated by compiler
};

DerivedEx“安全”吗?

为了安全起见,我一直假设我必须在 DerivedEx 中实现一个虚拟的空析构函数。但我想知道这是否是多余的和不必要的,以及是否有任何我不知道的“陷阱”。

最佳答案

是的,它仍然是安全的。

如果任何基类析构函数是虚拟的,则析构函数自动是虚拟的。无论您键入 ~Foo(); 还是 virtual ~Foo(); 或两者都不键入,这都是正确的,只允许编译器生成隐式定义的析构函数。

关于c++ - 在具有虚拟析构函数的基类的子类中不指定析构函数是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14281078/

相关文章:

c++ - libcurl C++ 在 POSTing JSON 时出现段错误

c++ - 如何通过管道发送/接收具有复杂数据结构的数据?

c++ - C++ 中的第一个覆盖前缀 - 我的代码有什么问题?

c++ - 从基类调用派生类函数

python - 类方法作为构造函数和继承

c++ - 如何推断模板中函数的返回类型

c++ - QMessageLogContext 的字段(如 : file, 函数、行)为空或为零

c++ - 链接列表示例 - 为什么使用它们?

c++ - 如何使用 vector 作为基类

java - 在 Java 中实现一个具体的类?