Cppcheck error: using dangerous iterators

Code:

for(x=abc.begin();x!=abc.end();x++) { if(-----) { ---- abc.erase(x); } } 

And the error:
Dangerous use of an iterator
After erasing, the iterator is invalid, so its dereferencing or comparison with another iterator is invalid.

What is the misuse when using the erase function in the above code?

+4
source share
4 answers

The iterator x is invalid after removing the corresponding value from abc. This should fix this:

 x = abc.begin(); while(x != abc.end()) { if (-----) { ---- x = abc.erase(x); // skipped only to next item } else { // skip only to next item ++x; } } 

The STL container erase template functions return the next element or end() .

Edit: Thanks for the comment from templatetypedef.

+5
source

You use x as a control variable in the loop. Since it is not valid using the erase () function, you cannot be sure that it is safe (or makes sense) to subsequently increase it at the top of the loop.

+5
source

x is a pointer to abc . Once you have removed the element that x points to, what should point to x and how should x++ work?

+4
source

You did not say anything about the container you are looking for. The type of container depends on which iterators are invalid. Obviously, the iterator for the element to be erased is invalid, but, for example, in std::vector all iterators that passed the element to be erased will be invalid (including end() ). And for an unknown reason, although set::erase only invalidates the iterator for the element to be erased, it does not return the iterator to the next element.

So std::set :

 while (x != abc.end()) // end() will not change and even can be stored { if (...) abc.erase(x++); // increments before erasing else ++x; } 
+1
source

Source: https://habr.com/ru/post/1343586/


All Articles