Re: STL Question: Safe to use elements after erasing them from the collection?

From: Gary Labowitz (glabowitz_at_comcast.net)
Date: 12/05/03


Date: Fri, 5 Dec 2003 12:41:24 -0500


"Ivan Vecerina" <please_use_web_form@ivan.vecerina.com> wrote in message
news:bqqd6o$ord$1@newshispeed.ch...
> "Generic Usenet Account" <usenet@sta.samsung.com> wrote in message
> news:90e5135.0312050833.7c1ea34@posting.google.com...
> | To settle the dispute regarding what happens when an "erase" method is
> | invoked on an STL container (i.e. whether the element is merely
> | removed from the container or whether it also gets deleted in the
> | process), I looked up the STL code.
> | Erase certainly does not delete the memory associated with the element.
> Most containers (excluding std::vector) may release the memory associated
> with items that have been removed using the erase member function.
<<snip>>
> According to the standard, the destructor of the erased elements
> *must* be called. It is not uncommon for code to rely on the
> deterministic destruction of the items being erased.
> Attempting to access items that have been erased leads to undefined
> behavior. Even if they were not destroyed immediately, hopefully
> the memory they occupy would be recycled at some point. So it
> wouldn't be safe to access the erased items either way.

Does this mean that it is bad behavior to put an object into two different
containers, or is that even possible?
(Forgive me for asking, but in Java it works differently. I was hoping it
worked similarly in C++.)

-- 
Gary


Relevant Pages

  • Re: STL Question: Safe to use elements after erasing them from the collection?
    ... | invoked on an STL container (i.e. whether the element is merely ... | removed from the container or whether it also gets deleted in the ... | Erase certainly does not delete the memory associated with the element. ... Most containers may release the memory associated ...
    (comp.lang.cpp)
  • Re: Locking an STL-like container
    ... i.e. it provides iterators by ... For locking the container while insertand erase() methods are ... executed I considered using scoped locks from the loki library. ...
    (comp.programming.threads)
  • Re: Sharing a RO std::list between 2 threads & Crash in _Orphan_ptr()
    ... But now you say you are calling methods on it that modify the list. ... It is, of course, illegal to modify a list while another thread is traversing it. ... So before starting the scan thread only one thread is accessing/modifying the std::list container. ... I call erase(), clearor removein my destructor when my shell extension is unloaded. ...
    (microsoft.public.vc.stl)
  • Locking an STL-like container
    ... i.e. it provides iterators by ... For locking the container while insertand erase() methods are ... executed I considered using scoped locks from the loki library. ...
    (comp.programming.threads)