c++ - 虚拟析构函数使用数组失败

标签 c++ polymorphism segmentation-fault new-operator virtual-destructor

我在 web site 上找到了这段代码

#include <iostream>

using namespace std;

struct Base
{
    Base() { cout << "Base" << " "; }
    virtual ~Base() { cout << "~Base" << endl; }

    int i;
};
struct Der : public Base
{
    Der() { cout << "Der" << endl; }
    virtual ~Der() { cout << "~Der" << " "; }

    int it[10]; // sizeof(Base) != sizeof(Der)
};

int main()
{
    Base *bp = new Der;
    Base *bq = new Der[5];

    delete    bp;
    delete [] bq;   // this causes runtime error
}

为什么会这样crash

最佳答案

Base *bq = new Der[5];
delete [] bq;   // this causes runtime error

原因是数组没有多态。因此,在上面的代码中,delete 语句调用了未定义的行为

§5.3.5/3 C++03 说

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

您很幸运,它给出了运行时错误,并且您有机会尽快发现代码中的严重错误。

关于c++ - 虚拟析构函数使用数组失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7754532/

相关文章:

c++ - 如何检查给定类型的变量是否可以取消引用?

c++ - 使用 FFmpeg SDK 将 .flv 转换为 mp3 的问题

scala - 通过特征覆盖方法时如何调用 super 方法

mongodb - 去 + MongoDB : polymorphic queries

C:使用 realloc() 转储核心

c - 在链表中,将最后一个节点与下一个元素进行比较会导致段错误吗?

c++ - "Segmentation fault"与 "run time"错误?

c++ - 传递给另一个函数时获取数组的长度

c++ - 多态性和方法重载在 C++ 中几乎是一回事吗

c++ - 函数模板的区别