Cleanup responsibility with pointers
To make the Stash and Stack
containers flexible (able to hold any type of object), they will hold
void pointers. This means that when a pointer is returned from the
Stash or Stack object, you must cast it to the proper type before
using it; as seen above, you must also cast it to the proper type before
deleting it or you’ll get a memory leak.
The other memory leak issue has to do
with making sure that delete is actually called for each object pointer
held in the container. The container cannot “own” the pointer
because it holds it as a void* and thus cannot perform the proper
cleanup. The user must be responsible for cleaning up the objects. This produces
a serious problem if you add pointers to objects created on the stack and
objects created on the heap to the same container because a
delete-expression is unsafe for a pointer that hasn’t been allocated on
the heap. (And when you fetch a pointer back from the container, how will you
know where its object has been allocated?) Thus, you must be sure that objects
stored in the following versions of Stash and Stack are made only
on the heap, either through careful programming or by creating classes that can
only be built on the heap.
It’s also important to make sure
that the client programmer takes responsibility for cleaning up all the pointers
in the container. You’ve seen in previous examples how the Stack
class checks in its destructor that all the Link objects have been
popped. For a Stash of pointers, however, another approach is
needed.