通过指向其基类的指针删除派生对象 [英] Deleting a derived object via a pointer to its base class
问题描述
我有两个类,base_class和derived_class和下面的代码:
base_class * ptr = new derived_class;
delete ptr;
这段代码会产生内存泄漏吗?
它不会泄漏你要删除的对象,它的内存块将会被释放。
如果您尚未在 base_class
中声明析构函数为虚拟,泄漏包含在 derived_class
中的任何动态分配的对象,这些对象依赖于调用 derived_class
的析构函数来释放它们。这是因为如果析构函数不是虚拟的,在这种情况下不会调用 derived_class
析构函数。这也意味着 derived_class
中的嵌入对象的析构函数不会被自动调用,这是一个单独的但是另外的问题,这可能导致进一步的泄漏和不执行重要的清除代码。
简而言之,将 base_class
中的析构函数声明为虚拟的,
有关编码示例,请参阅:
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屋!