Re: destructor of binary tree
On Jan 27, 4:53 pm, Jerry Coffin <jcof...@taeus.com> wrote:
In article <e67b05e1-d868-44c6-bea1-e3ad1c8d079c@
1g2000hsl.googlegroups.com>, a...@servocomm.freeserve.co.uk says...
On Jan 27, 12:13 am, xz <zhang.xi...@gmail.com> wrote:
Is this question too stupid to answer?
No , the question of the different nature of objects on the stack and
the heap is extremely interesting and even difficult.
The fundamental difference in semantics is, of course, that stack
objects are garbage collected, but heap objects arent.
One option that would work is to query the pointer:
void f (T * p)
{
if (is_on_heap(p)){
delete p;
}
else {
/* do nothing */
}
}
One slight problem... C++ has no obvious way to define the function
is_on_heap(p). IMO it should.
Therefore IMO it is a very interesting question :-)
While the standard library doesn't support it directly, the
standard allows you to replace ::new and ::delete, so you can
write your own that support them. The obvious way would be to
create a set of the addresses your ::new has returned.
is_on_heap() would then look something like:
template <class T>
bool is_on_heap(T *p) {
return heap_map.find((void *)p) != heap_map.end();
}
At least at first glance, there are only two things that look
tricky to me. The first is the simple situation that even
though replacing ::new and ::delete is officially supported,
it's sufficiently unusual that you might find your code
doesn't work with it. The second is that you have to ensure
heap_map doesn't use your replacement ::new to allocate its
own memory, or you'll run into infinite recursion.
The trickiest part takes place when you start dealing with
inheritance, particularly multiple or virtual inheritance. In
such cases, it's likely that the Base* given to is_on_heap
doesn't compare equal to an address ::operator new() returned.
(This can be solved, of course---operator new() has to save a
range in the heap_map---, but it's not quite as simple as is
avoiding infinite recursion.)
And of course, there will always be the un-co-operative user,
who dynamically allocates an array of nodes, or placement new's
them in dynamically allocated memory, expecting to use an
explicit delete later:-).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34