0

We're currently using Coverity's Synapsis which runs over the code base and flags lines of code that would cause a bug and such.

I have this code:

auto it = std::find_if(my_container.my_list.begin(), my_container.my_list.end(),
            [&](my_struct temp)
            {
                return temp._id == id;
            });

/*To erase duplicates*/
if (it != my_container.my_list.end())
{
     my_container.my_list.erase(it);
}

The erase part is being recognized as "erase invalidates iterator " then "Using invalid iterator (INVALIDATE_ITERATOR)". I'm not sure I understand why this is so. The iterator is not used after this code so it should be safe, right?

7
  • 1
    Why are you comparing it with the end() iterator from what appears to be a completely unrelated sequence? The iterator it is valid only within the space of my_container.my_list, not m_ue_params.ues.
    – WhozCraig
    Mar 20, 2018 at 6:01
  • @WhozCraig Good catch! I updated my code above, I just forgot to replace the variable names for my example so it would be more understandable what it represents Mar 20, 2018 at 6:05
  • it = my_container.my_list.erase(it); to update the iterator after the erase.
    – dgsomerton
    Mar 20, 2018 at 6:08
  • @dgsomerton Oh, I think I get it now, thanks. So it appears that it may still be used after it's erased? Mar 20, 2018 at 6:10
  • 1
    @phoenixWright Impossible for us to say. The code after this was not included, and you stated in your question that "The iterator is not used after this code...". As written, if it is never used after this, and the code shown exactly as it is here now, with your changes making my first comment irrelevant, should work. if it doesn't, something else is wrong that we can't see. Unrelated, my_struct temp should probably be a const reference unless you like making needless copies of things.
    – WhozCraig
    Mar 20, 2018 at 6:22

0

Your Answer

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

Browse other questions tagged or ask your own question.