加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – “删除”是否与多态性一起正常工作?

发布时间:2020-12-16 09:44:47 所属栏目:百科 来源:网络整理
导读:参见英文答案 Virtual destructor and undefined behavior????????????????????????????????????4个 BaseClass * p = new DerivedClass();delete p; 我知道第二行将调用基类的析构函数,如果它没有虚拟析构函数和派生类的析构函数,如果它有,但会正确删除内存(
参见英文答案 > Virtual destructor and undefined behavior????????????????????????????????????4个

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

我知道第二行将调用基类的析构函数,如果它没有虚拟析构函数和派生类的析构函数,如果它有,但会正确删除内存(让我们说BaseClass的对象占用8个字节的空间和DerivedClass的一个12 – 它将释放8或12个字节)并在任何一种情况下摆脱对象?

解决方法

好吧,如果它有一个虚拟析构函数,当然会破坏对象并按预期释放内存.如果它没有虚拟析构函数,则行为未定义.

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.

因此,试图判断内存是否将被完全解除分配并没有任何意义.程序可以用内存做任何喜欢的事情.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读