There are some very rare cases where you might not be able to use a smart pointer (probably dealing with old code), but cannot use a simple "ownership" scheme either.
Imagine you have an std::vector<whatever*>
and some of the whatever*
pointers point to the same object. Safe cleanup involves ensuring you don't delete the same whatever twice - so build an std::set<whatever*>
as you go, and only delete the pointers that aren't already in the set. Once all the pointed-to objects have been deleted, both containers can safely be deleted as well.
The return value from insert
can be used to determine whether the inserted item was new or not. I haven't tested the following (or used std::set for a while) but I think the following is right...
if (myset.insert (pointervalue).second)
{
// Value was successfully inserted as a new item
delete pointervalue;
}
You shouldn't design projects so that this is necessary, of course, but it's not too hard to deal with the situation if you can't avoid it.