虚拟析构函数使用数组失败 [英] virtual destructor fail using array

查看:150
本文介绍了虚拟析构函数使用数组失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网站找到此代码

#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 语句调用未定义的行为

The reason is arrays are not treated polymorphically. Therefore, in the above code, the delete statement invokes undefined behaviour.

§5.3.5/ 3 C ++ 03说

§5.3.5/3 C++03 says


第一个替代(删除对象),如果操作数的静态类型不同于其动态类型,则静态类型应为操作数动态类型的基类,静态类型应具有虚析构函数或行为未定义。 如果要删除的对象的动态类型与其静态类型不同,则在第二个替换(删除数组)中,行为是未定义的

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.

您很幸运,它提供了运行时错误,并且您有机会尽快知道代码中的一个严重错误。

You're lucky that it gives runtime-error, and you got the opportunity to know a serious bug in your code, as soon as possible.

这篇关于虚拟析构函数使用数组失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆