Found this (simplified version below) in some old code and the Debugger (VC++ 2015) did not complain about an invalid iterator while executing it.
#include <iterator>
#include <set>
int main() {
std::set<int> s = {0,1,2,3,4};
auto it = std::begin(s);
while (it != std::end(s))
{
if (*it % 2 == 0)
s.erase(it++); // UB?
else
++it;
}
}
I know it should be it = s.erase(it);
instead, but I was wondering if this actually is undefined behaviour. Is it, or is there something going on that renders the code OK?
The following would of course be undefined:
s.erase(it);
++it
And the now following would be OK:
auto temp = it;
++temp;
s.erase(it);
it = temp;
But what about my code above?
s.erase(it++);