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?