Mr.O
Mr.O

Reputation: 352

delete an object both from vector and memory while iterating

I trying to to delete an object both from a vector of objects and from memory using its destructor. I understood the deleting the the object that the iterator points to, is making the the iterator to point to the element that follows the last element removed. Therefore, I tried to implement this:

std::vector<Customer*>::iterator j=customersList.begin();
while (j!=customersList.end()){
    customersList.erase(j);
    delete  *j;
}

is it o.k. or that it jumps 2 places by applying both erase and delete?

Upvotes: 1

Views: 434

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

The loop is not correct, since

  1. you are invalidating the j iterator, and subsequent to that, issuing a delete call on the dereferenced, invalid iterator.

  2. The j iterator is not incremented at all in that loop.

The easiest way to issue a delete and erase is a simple std::for_each, followed by a vector::clear().

#include <algorithm>
//...
std::for_each(std::begin(customersList), std::end(customersList), [](Customer *c){delete c;});
customersList.clear();

or even simply:

for (Customer* c : customersList )
    delete c;
customersList.clear();

Upvotes: 3

Related Questions