调用析构函数是否完全破坏对象? [英] Does calling a destructor explicitly destroy an object completely?

查看:128
本文介绍了调用析构函数是否完全破坏对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我明确调用析构函数(myObject。〜Object()),这可以确保对象被适当地销毁(调用所有的子析构器)。

If I call a destructor explicitly ( myObject.~Object() ) does this assure me that the object will be appropriately destroyed (calling all child destructors) ?

确定一些代码:

class Object
{
   virtual ~Object()
   {}
};

class Widget : public Object
{
   virtual ~Widget()
   {}
};

...
Object* aWidget = new Widget(); //allocate and construct
aWidget->~Object(); //destroy and DON'T deallocate

我知道我可以删除对象, t想要。我想把分配的内存作为一个重要的优化。

I know I could just delete the object, but I don't want to. I want to keep the allocated memory handy as an important optimization.

谢谢!

推荐答案

答案是...几乎总是。

The answer is... nearly always.

如果你的对象有一个非虚拟析构函数,然后被子类添加子元素需要释放...然后调用析构函数对象基类不会释放子元素。这是为什么你应该总是声明析构函数virtual。

If your object has a non-virtual destructor, and is then sub-classed to add child elements that need freeing... then calling the destructor on the object base class will not free the child elements. This is why you should always declare destructors virtual.

我们有一个有趣的情况下,两个共享库引用一个对象。我们改变了定义以添加需要释放的子对象。我们重新编译了包含对象定义的第一个共享库。

We had an interesting case where two shared libraries referenced an object. We changed the definition to add child objects which needed freeing. We recompiled the first shared library which contained the object definition.

另一方面,第二个共享库没有被重新编译。这意味着它不知道新添加的虚拟对象定义。删除从第二个共享库调用,简单地调用free,并没有调用虚拟析构函数链。结果是一个讨厌的内存泄漏。

HOWEVER, the second shared library was not recompiled. This means that it did not know of the newly added virtual object definition. Delete's invoked from the second shared library simply called free, and did not invoke the virtual destructor chain. Result was a nasty memory leak.

这篇关于调用析构函数是否完全破坏对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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