Virtual Destructor - Implication & Specification
Hi All,
A while back I originated a post about a Virtual_Destructor<> wrapper
template whose purpose was simply to add a no-op virtual destructor to
a class. Using it. at least under Microsoft Windows, circumvents the
new/delete heap mismatch problem.
Over the years I have had repeated arguments with colleagues who
emphatically insist that making the destructor of a class virtual
under Windows will *not* eliminate the heap mismatch problem, and each
time, I have to write an EXE and a companion DLL to prove that it
does.
In the future, I would rather be able to defer to the standard instead
of writing demonstration code. The problem is that Stroustrup has
been somewhat vague in his his description of the implication of a
virtual destructor. In particular, in TCPPPL 3rd Edition, page 422,
last paragraph, he writes in the context of class-specific new and
delete, for the famous Employee/Manager example, what the programmer
should do to make sure that deletion a manager via pointer-to-Employee
guarantees proper deallocation:
*** BEGIN QUOTE ***
Even an empty destructor will do:
Employee::~Employer() {}
In principle, deallocation is then done from within the destructor
(which knows the size). Furthermore, the presence of a destructor in
Employee ensures that every class derived from it will be supplied
with a destructor (thus getting the size right), even if the derived
class doesn't have a user-defined destructor.
*** END QUOTE ***
The key phrase in this paragraph is "done from within the
destructor." Yes, I realize that the "In principle.." part is very
important, as it would be highly awkward for the compiler writer to
actually put the freeing of memory portion inside the tilde (~)
function.
However, what I would like to know is what the standard says about
virtual functions and the
1. tilde(~)
2. /free()
....sequence. [Note that I am purposely avoiding calling the ~function
the destructor for rhetorical reasons.]
Is there any place in the standard that states explicitly that this
sequence occurs through the virtual machinery for any class that has a
virtual destructor?
Also, I imagine a situation where my solution to the heap mismatch
problem would fail, whereby the compiler would look into the object,
invoke the correct tilde (~) function via the v-table, retrieve the
actual size of the object while inside the v-table space, then, upon
returning, invoke the wrong free using that size. Technically, the
appropriate destructor will have been invoked, and the right size
used, but the program will crash.
So, as one can see, the "In principle, deallocation is done from
within the destructor..." is critical.
What does the standard say about this? How much of the deallocation
sequence is guaranteed to be controlled by deference to the virtual
function mechanism?
-Le Chaud Lapin-
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]