2
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?

3
  • that depends on implemention. its better to use [en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom](erase-remove idiom) Commented Apr 1, 2015 at 13:20
  • @BruceAdi Erase-remove only works for sequence containers, not for associative ones. Commented Apr 1, 2015 at 13:59
  • 3
    Surely its better just to call clear() on the map. Commented Apr 1, 2015 at 15:03

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd go further. Even if the ++ 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!
@AaronMcDaid I believe the two operations (increment and call) are indeterminately sequenced; if the increment happens first, it's OK, if the call happens first, it's UB as you say. But your words regarding the return value of erase are very wise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.