[Interest] QList and erase problem...

André Somers andre at familiesomers.nl
Mon Sep 14 17:06:08 CEST 2015


Op 14-9-2015 om 16:57 schreef Igor Mironchik:
> Hi,
>
> I ran into this problem...
>
> void
> ImageFilesStoragePrivate::removeAllImages(
>       QList< ImageRecord > & images,
>       ImageFilesStorage::ImageType type )
> {
>       QList< ImageRecord >::Iterator it = images.begin();
>       QList< ImageRecord >::Iterator last = images.end();
>
>       while( it != last )
>       {
>           if( (*it).m_type == type )
>           {
>               LOG( DebugLogLevel, "Before real deletion" )
>               removeFromDatabase( it );
>               LOG( DebugLogLevel, "After real deletion" )
>
> //            it = images.erase( it ); // LOOK AT THIS LINE !!! If I
> uncomment it and comment next line - crash...
>               ++it;
>
>               LOG( DebugLogLevel, QString( "it == last : %1" ).arg( ( it
> == last ? "true" : "false" ) ) )
>           }
>           else
>               ++it;
>       }
> }
>
> What is wrong?
A lot is wrong.

First, you are not using standard algorithms to do standard things. I'd 
say std::remove_if with std::erase would be a better way to solve the issue.

Then in general, if you delete from the container, iterators are going 
to be invalidated. Iterate backwards if you are going to delete items 
from the container.

Last: you probably don't want to use QList but QVector.

André





More information about the Interest mailing list