Topic: list<A*>::erase
Author: "P.J. Plauger" <pjp@dinkumware.com>
Date: 1998/06/17 Raw View
Marc Ferry <marc@netmansys.fr> wrote in article <35867306.F1A70DF6@netmansys.fr>...
> I am getting confused about the erase() method of a list.
> I would like to remove (and delete) the first element of
> a list containing pointers. Among the following methods,
> which one do you suggest ?
>
> void X::removeAndDeleteFirst(list<A*>& a_ptr_list)
> {
> list<A*>::iterator it = a_ptr_list.begin();
> a_ptr_list.erase(it);
> // Memory leak ?
Yes, try instead:
if (it != a_ptr_list.end())
{delete **it;
a_ptr_list.erase(it); }
ASSUMING that each element of the list ``owns'' the object designated
by the pointer it stores. (The designated object should die when the
pointer dies.)
> void X::removeAndDeleteFirst(list<A*>& a_ptr_list)
> {
> list<A*>::iterator it = a_ptr_list.begin();
> delete it;
DISASTROUS. You're deleting an automatic object.
> a_ptr_list.erase(it);
> }
>
> void X::removeAndDeleteFirst(list<A*>& a_ptr_list)
> {
> list<A*>::iterator it = a_ptr_list.begin();
> A *a = *it;
> a_ptr_list.erase(it);
> delete a;
This is an acceptable variation of what I showed above, except that
you really should test for an empty list.
> In other words, does the call to erase() also remove the
> pointed object, or should a delete be called on the pointed
> object ?
Trust the list to delete any object it stores. In this case, it stores a
pointer, so deleting it does nothing. As always, it's up to you, the
programmer, to know what to do (if anything) with the object pointed
at (if any).
> In the second case, when should it be done (after
> or before the call to erase()) ?
Doesn't matter, unless you're worrying about keeping the list in
a coherent state in a multithreaded environment, in which case
you have LOTS more to worry about.
P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]