Virtual Destructor and Templates: A Crazy Doubt

Started by
9 comments, last by MaulingMonkey 18 years, 1 month ago
Quote:Original post by Polymorphic OOP
Quote:Original post by MaulingMonkey
Further, since C++ requires a virtual destrcutor in order to properly delete a derived class through a pointer-to-base class, all interfaces should have a virtual destructor.

It's quirky enough behavior that it has been at least proposed, if not decided upon, for the next revision of C++ ("C++0x") that if a class contains any virtual functions, that the destuctor will automatically become virtual.

That's not true, which is why it isn't standard already. Not all interfaces should have a virtual destructor. The only time a destructor would have to be virtual is if you are to delete children of the type via a pointer to the base. Not all types which have virtual functions are deleted via a pointer to base, which is why you are given the choice.


"All" and "automaticlly" were a bad choice of words (I suppose). "99.9% of" and "by default" would have been better - (the later of which is what Bjarne Stroustrup proposes - see the final section, under the bullet "Remove embarrassments"). The costs are an added entry for the vtable, and a (possible) vtable lookup on delete - which will hardly be the most expensive component of freeing memory - and that will only be when the compiler can't be certain of the type that it's deleting.

The likelyhood of a non-virtual dtor being an appropriate optimization being as slim as it is (the bottleneck really is freeing objects, and it really has nothing to do with your memory manager?!?), and the bountiful opportunities for added debugging costs that this optimization brings (undefined behavior on delete-through-base), it makes no sense for it to be the default. The fact that it currently is the default reflects on oversight rather than appropriateness. And it is with some reservation that I downgrade my statement from "all" to "99.9%" - chances are, if a vtable lookup there is really all that bad, you've got a bigger problem with far better optimization techniques available which should be focused upon, rather than distracting yourself with this minor optimization.

This topic is closed to new replies.

Advertisement