Notes to Migration of CorbaFreeDynaMIT (6)
Iterators
Iterators are a generalization of pointers: they are objects that point to other objects. In most situations we could instead use a pointer when an iterator is required, and even under some circumstance, the compiler will actually optimize iterators into pointers when creating the object codes. Iterators, however, are not necessarily implemented by pointers. For example, vector::iterator is not T*; string::iterator is not char*. Hence converting iterators to pointers is considered dangerous, and is likely to make our code broken.
The STL offers several predefined iterators, with different behavior. For example, the input iterators only guarantee read access. Selecting the correct type of iterators is one of the tasks we must face when migrating CorbaFreeDynaMIT.
Where does it occur? Most classes that use STL containers (vectors, pair, etc.) For example, in the getODID member function of class dtaMappingOD, using a writable iterator will cause an error: "invalid conversion from 'const idlOrigDestID* const' to 'idlOrigDestID*'."
Another example is we should not test whether a iterator is null pointer or not. The following code is invalid:
std::vector::iterator jIterator;
for( jIterator= iIterator->begin(); jIterator != iIterator->end(); jIterator++ )
{
if( jIterator ) { // i.e., if (jIterator != NULL )
// do something...
}
}
How to fix: Use const_iterator instead of the default iterator, and avoid unnecessary type conversion. Make sure we have include the proper header file, i.e.,