Rule Definition
While iterating over a container almost all modifications of said contained will invalidate the iterator and bring undefined behaviour. Moreover the encapsulation in a class can mask that we are modifying the container by the use of class method and consequently invalidate the iterator.
Remediation
Do not modify the container while iterating over, unless you modify the iterator itself.
Violation Code Sample
class A{
std::vector<int>& getVector();
void removeElement(int index);
private:
std::vector<int> m_integerVector;
};
void func(){
A a;
...
for(int val : a.getVector()){
...
a.removeElement(index);
...
}
}
Fixed Code Sample
class A{
std::vector<int>& getVector();
void removeElement(int index);
private:
std::vector<int> m_integerVector;
};
void func(){
A a;
...
for(int val : a.getVector()){
...
}
...
a.removeElement(index);
}
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.