这是否有一个定义的行为,这个代码通过基类指针删除派生类? [英] Is this there a defined behavior for this code that deletes a derived class through a base class pointer?

查看:131
本文介绍了这是否有一个定义的行为,这个代码通过基类指针删除派生类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码是否导致定义的行为?

Does this code result in defined behavior?

class A {
    int x;
};
class B {
    short y;
};
class C {
    double z;
};

class D : public A, public B, public C {
    float bouncy;
};

void deleteB(B *b) {
    delete b;
}

void is_it_defined() {
    D *d = new D;
    deleteB(d);

    B *b = new D;  // Is this any different?
    delete b;
}

如果没有定义,为什么不?如果是,它是什么定义,为什么?最后,如果它的实现定义,你能举一个常见的实现可以定义的行为的例子吗?

If it's not defined, why not? And if it is, what's it defined to do and why? Lastly, if it's implementation defined, could you give an example of what a common implementation might define the behavior to be?

推荐答案

Herb Sutter


如果删除可以通过基类
接口多态地执行
,则它必须虚拟地表示
,并且必须是虚拟的。事实上,
语言需要它 - 如果你
删除多态而没有
虚拟析构函数,你召唤
dreaded的幽灵的未定义
行为。

If deletion can be performed polymorphically through the base class interface, then it must behave virtually and must be virtual. Indeed, the language requires it - if you delete polymorphically without a virtual destructor, you summon the dreaded specter of "undefined behavior".

在您的示例中, delete 都是通过基类指针执行的,并产生未定义的行为。标准5.3.5(删除):

In your example, both delete are performed through base class pointers and yield undefined behavior. Standard 5.3.5 (Delete) :


在第一个替代方法中(删除
对象),
操作数与其动态
类型不同,静态类型应为操作数动态类型
的基本
类,静态类型应有
虚拟析构函数或行为是
未定义

/ code>对静态类型进行操作,而操作数的动态类型为 D

Here, both delete act on static type B while the operand's dynamic type is D.

这篇关于这是否有一个定义的行为,这个代码通过基类指针删除派生类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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