我想知道为什么在继承中调用析构函数会出错

I wonder why there is an error calling the destructor in the inheritance

#include<iostream>
using namespace std;

class A
{
public:
   A() { cout << "A Creator" << endl; }
   ~A() { cout << "A Destroyer" << endl; }
};

class B : public A
{
public:
    B() { cout << "B Creator" << endl; }
    virtual ~B() { cout << "B Destroyer" << endl; }
};

void main()
{
    A* temp = new B;
    delete temp;
}

我不确定我是这么想的。 我很想知道为什么会发生错误。

temp 分配派生的 class B 并将其存储在指针类型(基础 class A)中。

此时编译器是基于指针数据类型

未创建虚函数 table,因为基 class 析构函数没有虚声明。

Class B 创建虚函数table。还创建了一个虚函数 table 指针。

当试图销毁 temp 时,temp 调用指针数据类型析构函数并发出问题。

ClassB虚函数table找不到指针

这是因为指针数据类型是非虚基class。

delete 如果指针指向基类子对象,则指针类型没有虚析构函数的指针具有未定义的行为。 temp 指向 B 实例的基础子对象并且 A::~A 是非虚拟的。

要修复,请声明 A::~A 虚拟。

您的代码调用 undefined behavior。 摘自 Scott Meyers 的 "Effective C++" 书解释了原因:

When derived class object is deleted through a pointer to a base class with a non-virtual destructor, results are undefined.

你的基础 class A 应该有一个虚拟析构函数:

virtual ~A() { std::cout << "A Destroyer" << '\n'; }

如果 classes 打算以多态方式使用,那么基础 class 应该有虚拟析构函数。