Bug 359306

Summary: new check idea: avoid using Q_FOREACH to iterate over QMap/QHash keys and retrieve values inside loop
Product: [Developer tools] clazy Reporter: Nyall Dawson <nyall.dawson>
Component: generalAssignee: Sergio Martins <smartins>
Status: RESOLVED FIXED    
Severity: wishlist CC: smartins
Priority: NOR    
Version: unspecified   
Target Milestone: ---   
Platform: Other   
OS: Linux   
Latest Commit: Version Fixed In:
Sentry Crash Report:

Description Nyall Dawson 2016-02-12 09:37:55 UTC
Eg:

QMap<QString,QString> map;

Q_FOREACH( const QString& key, map.keys() )
{
   QString val = map.value(key);
   ...
}

It's inefficient, and it'd be nice to catch this and suggest using QMap::iterator/QHash::Iterator to iterate over both the keys and values at the same time to avoid the unnecessary lookup.



Reproducible: Always
Comment 1 Sergio Martins 2016-02-15 19:07:36 UTC
The container-anti-pattern will warn when you iterate on keys(), which you should fix with:

Q_FOREACH( const QString& value, map) {}, or using iterator if you need both value and key.
There might be corner-cases where people are doing something very stupid, but it's difficult to make a check for more imaginative cases, so I consider this done