I got this strange issue following is the code snippet which is working properly.
std::multimap<long,int>::iterator dateItr = reconnQueueDates.begin();
while( dateItr!=reconnQueueDates.end() ){
LOG_DEBUG("RUN comparision " <<cDateTime<< ", "<<dateItr->first);
if(dateItr->first <= cDateTime){
long nextTimeout = -1;
if( (nextTimeout = callReconnects(dateItr->second,dateItr->first))>-1){
if(nextTimeout>0){
reconnQueueDates.insert(std::pair<long , int>(nextTimeout, dateItr->second));
}
reconnQueueDates.erase(dateItr);
LOG_DEBUG("modified the iterator ressetting");
dateItr = reconnQueueDates.begin();
LOG_DEBUG("resset iter");
}//end of callreconnect if
}else{
++dateItr;
} //else for datetime check
}//end of while
Before this I was using a for loop with ++dateItr in the loop as follows
for( ;dateItr!=reconnQueueDates.end();++dateItr ){
LOG_DEBUG("RUN comparision " <<cDateTime<< ", "<<dateItr->first);
if(dateItr->first <= cDateTime){
long nextTimeout = -1;
if( (nextTimeout = callReconnects(dateItr->second,dateItr->first))>-1){
if(nextTimeout>0){
reconnQueueDates.insert(std::pair<long , int>(nextTimeout, dateItr->second));
}
reconnQueueDates.erase(dateItr);
LOG_DEBUG("modified the iterator ressetting");
dateItr = reconnQueueDates.begin();
LOG_DEBUG("resset iter");
}// callReconnect
} // check datetime
}// for loop
While debugging I found out that after changing the map inside the loop the iterator value inside the for construct was still using the old address.
I am using and ubuntu 12.04 with g++ version 4.6.3. Seems to me some kind of compiler bug or some kind of optimization doing this.
Any idea which flag or a bug it might be.
After
reconnQueueDates.erase(dateItr);the iterator indateItris invalid and any use of it is undefined behaviour. Since both your old and your newforloop use it afterwards, the fact that your new version “works” is purely accidental.The correct way to do it is to first extract all data you might still need (including the position of the next iterator) before erasing that element. For example: