-1

I'm currently facing a strange problem: I have a std::list of pointers and I want to clear it and to delete all of its items.

So, I've written a small piece of code:

for (std::list<IClientSocket *>::iterator it = mClients.begin(); it != mClients.end(); it = mClients.erase(it))
  delete *it;

I've never had problems with this code when I run it on Linux, but on Windows I get an exception list iterator is not incrementable.

I've tried differend alternatives (using while (!list.empty()) or pop_back instead of iterators), but I got the same issue. The only solution I've found is to erase the item before deleting the pointer it contains:

 std::list<IClientSocket *>::iterator it = mClients.begin();
 std::list<IClientSocket *>::iterator end = mClients.end();

 while (it != end) {
   IClientSocket *client = *it;
   it = mClients.erase();
   delete client;
 }

I can't understand why I get this exception. I've read that erase invalidate the iterator, but delete don't (this is quite logical)... Moreover, when i run the program via VisualStudio, it raises the exception. But when i run the same program on Cygwin, it works fine...

Have I missed something?

Simon Ninon
  • 2,371
  • 26
  • 43
  • `std::list::erase()` has mandatory parameters. This code would also disappear completely if you made use of something that cleans itself up. – chris Sep 20 '14 at 22:17
  • I can't reproduce this on my Visual Studio (using a `std::list`). – T.C. Sep 20 '14 at 22:21
  • 1
    @Cyber: I can see no place in the shown code where Simon uses a deleted iterator. Notice that the increment part of the for loop is `it = mClients.erase(it)`. – Bill Lynch Sep 20 '14 at 22:26

1 Answers1

3

"list iterator is not incrementable" is a bit of a tip-off. You don't show all your code, and in particular there's no list iterator increment shown. Apparently that's happening inside the delete then. You're not by any chance trying to iterate over the container when you're in the dtor of one of its elements?

MSalters
  • 173,980
  • 10
  • 155
  • 350