jeudi 11 août 2022

Is post-incrementing the iterator during a container erase always a bug?

Debugging some code, I found an invalid use of an iterator. So I searched our code-base for further bad usages. I found a few of these:

it = cppContainer.erase( it++ );

(Where it is a valid container iterator before this line, and cppContainer is a STL container, e.g. vector).

This sparked a discussion on whether the it++ was merely redundant, or whether it was post-incrementing the iterator after the call to the container .erase() made it invalid, which would be bad.

Is this form always a bug? Obviously the ++ is unnecessary, but is it wrong?

The general consensus among the engineers was that it was potentially bad.

Aucun commentaire:

Enregistrer un commentaire