Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calling a destructor explicitly destroy an object completely?

Tags:

c++

destructor

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!

like image 350
Robert Gould Avatar asked Jun 24 '09 01:06

Robert Gould


1 Answers

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.

like image 162
the.jxc Avatar answered Sep 21 '22 20:09

the.jxc