通过指向其基类的指针删除派生对象 [英] Deleting a derived object via a pointer to its base class

查看:96
本文介绍了通过指向其基类的指针删除派生对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,base_class和derived_class和下面的代码:

  base_class * ptr = new derived_class; 
delete ptr;

这段代码会产生内存泄漏吗?

解决方案

它不会泄漏你要删除的对象,它的内存块将会被释放。



如果您尚未在 base_class 中声明析构函数为虚拟,泄漏包含在 derived_class 中的任何动态分配的对象,这些对象依赖于调用 derived_class 的析构函数来释放它们。这是因为如果析构函数不是虚拟的,在这种情况下不会调用 derived_class 析构函数。这也意味着 derived_class 中的嵌入对象的析构函数不会被自动调用,这是一个单独的但是另外的问题,这可能导致进一步的泄漏和不执行重要的清除代码。



简而言之,将 base_class 中的析构函数声明为虚拟的,

有关编码示例,请参阅:



在什么样的情况下,c ++析构函数不会被调用?


I have two classes, base_class and derived_class and the following code:

base_class *ptr = new derived_class;
delete ptr;

Will this code produce a memory leak? If so, how should I deal with it?

解决方案

It won't leak the object you are deleting, its memory block will be freed.

If you have not declared the destructor in base_class to be virtual then it will leak any dynamically allocated objects contained within derived_class that rely on the destructor of derived_class being called to free them. This is because if the destructor is not virtual, the derived_class destructor is not called in this case. It also means that destructors of "embedded objects" within derived_class will not automatically be called, a seperate but additional problem, which can lead to further leaks and the non-execution of vital cleanup code.

In short, declare the destructor in base_class to be virtual and you can safely use the technique you have presented.

For a coded example, see:

In what kind of situation, c++ destructor will not be called?

这篇关于通过指向其基类的指针删除派生对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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