是否“删除"?多态性可以正常工作吗? [英] Does "delete" work properly with polymorphism?

查看:105
本文介绍了是否“删除"?多态性可以正常工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

BaseClass * p = new DerivedClass();
delete p;

我知道第二行将在没有虚拟析构函数的情况下调用基类的析构函数,而在没有派生类的情况下调用派生类的析构函数,但会正确地释放内存(假设BaseClass' s对象占用8个字节的空间,而DerivedClass占用1个12的空间-它会释放8个字节还是12个字节)并在两种情况下都摆脱掉对象?

I know the 2nd line will call the destructor of the base class if it doesn't have a virtual destructor and that of the derived class if it does but will delete properly free the memory (let's say BaseClass's object takes up 8 bytes of space and DerivedClass's one 12 - will it free 8 or 12 bytes) and get rid of the object in either case?

推荐答案

如果它具有virtual析构函数,则当然该对象将被销毁并按预期方式释放内存.如果它没有virtual析构函数,则行为是不确定的.

Well in the case that it has a virtual destructor, of course the object will be destroyed and the memory deallocated as expected. If it doesn't have a virtual destructor, the behaviour is undefined.

如果要删除的对象的静态类型与其动态类型不同,则静态类型应为要删除的对象的动态类型的基类,并且静态类型应具有虚拟析构函数或行为是未定义的.

if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

因此,试图推断内存是否将被完全释放并没有任何意义.该程序可以对内存执行任何操作.

So it doesn't really make any sense to attempt to reason about whether the memory will be fully deallocated or not. The program can do whatever it likes with the memory.

这篇关于是否“删除"?多态性可以正常工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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