map<int, int> m_map;
// ...
map::iterator it = m_map.begin();
while (it != m_map.end())
{
m_map.erase(it++);
}
When does the ++ action take place? Is it before or after the erase? When would it be safe to do so?
I don't think it's specified whether the ++ happens before or after the call to erase. Still, even if it was guaranteed to be peformed before the call, the fact that you had to asks shows that the code is bad. There is a better, 100% safe alternative:
while (it != m_map.end())
{
it = m_map.erase(it);
}
erase returns an iterator to the element past the erased one.
++ happens after the call (which is I think it does), it will still be undefined behaviour. It is meaningless to increment an iterator which points at an item which has already been erased. My rule of them is that I should never ignore the return value from a call to erase as the return value is probably the only well-defined thing I have access to!erase are very wise.
clear()on the map.