Programming in C++ the STL comes in handy. The use of the various container classes, iterators etc. are very convenient. But there can be some pitfalls. For example look at this piece of example code:
erbium doped fiber amplifier#include <vector> #include <iostream> using namespace std; int main() { vector<int> v; v.push_back( 1 ); v.push_back( 2 ); v.push_back( 3 ); v.push_back( 4 ); v.push_back( 5 ); for( vector<int>::iterator iter = v.begin(); iter != v.end(); ++iter ) { cout << *iter << endl; if( *iter == 2 ) { v.push_back( 99 ); } } }
Do you see the error? No?
Compile it, run it, it will probably succeed.
But there is a small error: when calling push_back() you are probably invalidating the iterator. Tthis is not true for every case, but for sure if the vector has to resize itself. And as you don’t know how vector is implemented, this code is dangerous.
But how to find these things? As you told you, it will compile and may be run even without error. You could do a code review; but real code is not as simple as this and may be your collegues do not know about these kind of pitfalls or simply do not spot this. Write unit tests? Yes of course, but the the size of your vector will be variable during runtime and you may not find the right condition to make the program fail. And if it fails it may fail at a complete different position, even the debugger might tell you something you won’t associate with this error.
Use the STL debug library! Compile with -D_GLIBCXX_DEBUG and the program will fail with the output:
1
2
/usr/include/c++/4.2/debug/safe_iterator.h:209:error: attempt to increment
a singular iterator.
Objects involved in the operation:
iterator "this" @ 0x0xbff55c60 {
type = N11__gnu_debug14_Safe_iteratorIN9__gnu_cxx17__normal_iteratorIPiNSt6__norm6vectorIiSaIiEEEEENSt7__debug6vectorIiS6_EEEE (mutable iterator);
state = singular;
references sequence with type 'NSt7__debug6vectorIiSaIiEEE' @ 0x0xbff55c60
}
Aborted
Ok. you have to understand this error message either, but clearly you see it is something going wrong with your iterator.