Search code examples
c++dictionaryiteratordelete-operator

Does Clear() method of STL containers calls delete on heap objects?


Possible Duplicate:
Does std::vector.clear() do delete (free memory) on each element?

I have a map where second elements are heap allocated.

Shall I explicitly call delete while iterating or does method erase() and clear() do that for me?

Here is my destructor which erases second element that are allocated with new

        ~Event()
        {
            auto iter = mapper.begin();
            while (iter != mapper.end())
            {                   
                mapper.erase(iter++); // heap object
            }
        }

Solution

  • You will have to explicitly call delete on each new element.
    Standard Library containers do not take ownership of the dynamic memory allocated to pointers.

    You should use Smart pointers as container elements if you need automatic cleanup.