List Iterators, erase() -- help
Hey,
I was wondering what happened if you erased an object from a list using an iterator, so I tried it, here's my code:
Code:
#include <list>
#include <iostream>
int main()
{
std::list<int> myList;
for (int i = 0 ; i < 10 ; ++i)
myList.push_back(i);
std::list<int>::iterator iter;
std::list<int>::iterator it2;
it2 = myList.begin();
it2++;
it2++;
it2++;
for (iter = myList.begin() ; iter != myList.end() ; ++iter)
{
std::cout << (*iter) << std::endl;
if ((*iter) == 5)
myList.erase(it2);
}
for (iter = myList.begin() ; iter != myList.end() ; ++iter)
std::cout << *iter << std::endl;
}
Here's where it gets weird, the part in blue, if that's it2, works fine, if it's "iter", under Solaris, it works fine, under cygwin (g++ 3.4.4) I get this:
Code:
$ ./a.exe
0
1
2
3
4
5
13501152
1628741068
1628741060
1 [main] a 2700 _cygtls::handle_exceptions: Error while dumping state (probably corrupted stack)
Segmentation fault (core dumped)
Now obviously the iterator is getting lost, which is why I'm getting some random value for where the 7th index SHOULD be...but my question is, why?
This code shouldn't create any undefined behavior, should it? Is it just undefined behavior that Solaris is handling differently than Cygwin? Or is Cygwin at fault?
I've never had issues with Cygwin, which is why I'm a bit concerned. If this is Cygwin's fault it definitely makes me want to try MinGW... Does anybody have any opinions on that, the major difference as I understand is that MinGW converts calls to the Win32 forms, as Cygwin uses its cyg<whatever>.dll to do the conversions, so MinGW doesn't rely on runtime call conversions?
TIA!