c++ - 派生类中是否需要显式声明的析构函数?

标签 c++ virtual destructor

考虑以下代码片段:

class A
{
virtual void function();
public:
  virtual ~A() {};
}

class B: public A
{
virtual void function() override final;
public:
  /*virtual*/ ~B() {}; // does this d-tor have to be declared at all?
}

我可以轻松找到有关基类析构函数的信息,例如http://en.cppreference.com/w/cpp/language/destructor

"Deleting an object through pointer to base invokes undefined behavior unless the destructor in the base class is virtual. A common guideline is that a destructor for a base class must be either public and virtual or protected and nonvirtual"

基类中的虚析构函数是必须的,那么派生类的析构函数呢,是否必须显式声明/定义?我觉得这很令人困惑,因为派生类的析构函数也自动是虚拟的。就 vtable 寻址而言,跳过派生类的析构函数的声明/定义是否合法?那么下面的情况呢:

class A
{
virtual void function();
public:
  virtual ~A() {};
}

class B: public A
{
virtual void function() override;
public:
  /*virtual*/ ~B() {}; // does this d-tor have to be declared at all?
}

class C: public B
{
virtual void function() override final;
public:
  /*virtual*/ ~C() {};  // does this d-tor have to be declared at all?
}

最佳答案

无需在派生类中显式定义析构函数。根据 C++ 标准

If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual

另外,如果您担心访问控制,那么

An implicitly declared destructor is an inline public member of its class.

编译器会将其隐式定义的析构函数的地址放在 vtable 中。所以派生类的vtable会存储派生类的析构函数地址。

为了代码的可读性,您可以编写示例

class B: public A
{
virtual void function() override final;
public:
  virtual ~B() = default;
}

关于c++ - 派生类中是否需要显式声明的析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21766854/

相关文章:

c++ - 我可以在 C++ 中有一个 ifstream 数组吗

c++ - mfc++中如何将char*转成char**

c++ - CURL 并将文件发送到服务器

linux - 在Linux中,如何连接两个vNIC?

c++ - 如何在C++中删除一个char*数组

python - 是否可以使用 libclang python 解析没有 header 的 cpp 文件中的函数原型(prototype)

c++ - 在类声明中使用 virtual 关键字

c++ - C++中虚函数和继承的实现

c++ - 类对象的 vector

c++ - gdb 可以中断隐式类方法吗?