Does calling a destructor explicitly destroy an object completely?
If I call a destructor explicitly ( myObject.~Object() ) does this assure me that the object will be appropriately destroyed (calling all child destructors) ?
Ok some code:
class Object
{
virtual ~Object()
{}
};
class Widget : public Object
{
virtual ~Widget()
{}
};
...
Object* aWidget = new Widget(); //allocate and construct
aWidget->~Object(); //destroy and DON'T deallocate
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.
Thanks!
The answer is... nearly always.
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.
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.
Yes. But holy smokes, are you sure about this? If so I would use placement new
to construct your Widget
. Using placement new
and then explicitly calling the destructor is an acceptable, if unusual, idiom.
Edit : Consider allocating the memory yourself manually rather than using new
to allocate the first object and then re-using its memory afterward. That allows you complete control over the memory; you could allocate big chunks at a time, for instance, rather than allocating a separate block of memory for each Widget
. That'd be fair savings if memory really is such a scarce resource.
Also, and perhaps more importantly, you'd then be doing placement new
"normally", rather than this hybrid regular new
/placement new
solution. I'm not saying it won't work, I'm just saying it's a rather, ah, creative solution to your memory problem.
Yes, a destructor, even when called explicitly, will destroy its subobjects properly.
As you seem to realize, it's a rare action to do, but perhaps as part of a well tested and documented library it may be useful. But document (and profile) it since even though it's valid and safe, every maintainer (including you) will never feel comfortable with it.
链接地址: http://www.djcxy.com/p/82808.html上一篇: 一个析构函数可以递归吗?
下一篇: 调用析构函数是否完全破坏对象?