尝试删除指向派生对象的基指针时断言错误

Assertion error attempting to delete base pointer to derived object

本文关键字:指针 断言 错误 对象 删除 派生      更新时间:2023-10-16

在C++研究继承时,我了解到用于多态行为的基类应该将其析构函数实现为virtual

我以为我知道如何很好地应用它,但我遇到了一个我不明白的小问题。

给定以下代码:

#include <iostream>
struct Base
{
Base() { std::cout << "Base ctor calledn"; };
virtual ~Base() { std::cout << "Base dtor calledn"; };
};
struct Derived : Base
{
Derived() : Base() { std::cout << "Derived ctor calledn"; }
~Derived() { std::cout << "Derived dtor calledn"; };
};
int main()
{
Derived d;
Base *p_base = &d;
delete p_base; //Problem here?
return 0;
}

输出符合预期:

Base ctor called
Derived ctor called
Derived dtor called
Base dtor called

但是,发生_CrtisValidHeapPointer(block)断言错误。

如果p_base直接指向一个新的Derived对象,一切正常,即Base *p_base = new Derived();

这里有什么不同?

亲切问候

问题是本地构造的对象d将在其作用域结束时自动删除,在您调用return 0的情况下。但是当时,您已经删除了指向同一对象的p_base。因此,该对象将被删除两次。

您的问题与继承无关。即使同一类的对象也应该出现。