0

When iterating through an STL::vector of pointers, what is the best practice for deleting objects along the way?

I understand the erase-remove idiom. But since the vector contains pointers, I am concerned that this will only delete the pointer, but leave the instances hanging around in memory.

For example, I would do something like

std::vector<someClass*> someClassList
std::vector<someClass*>::iterator i;

for (i=someClassList.begin(); i != someClassList.end(); ++i){
    determine_if_should_be_deleted(i);
    // <--How to delete the object and remove it from the vector without 
    // <--messing up the iterator?
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
M F
  • 7
  • 4
  • Is it not possible to use smart pointers here? – risingDarkness Oct 05 '15 at 13:31
  • 2
    with `std::vector>`, you may simply use erase-remove idiom. – Jarod42 Oct 05 '15 at 13:32
  • Only use *non-owning* raw pointers in STL containers, i.e. if you use them as references. If the container needs to own the resources use a smart pointer (except `auto_ptr`) or one of [Boost's pointer containers](http://www.boost.org/doc/libs/release/libs/ptr_container/doc/ptr_vector.html). – Brandlingo Oct 05 '15 at 14:12

1 Answers1

0

If you used new to create each instance, then

delete *i;

will do the job. You won't mess up your iteration since you're not removing the pointer from the vector, but you're releasing the memory that's being pointed to.

A better technique would be to use std::unique_ptr though, then the std::vector destructor will take care of releasing memory.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483