Bug 359306 - new check idea: avoid using Q_FOREACH to iterate over QMap/QHash keys and retrieve values inside loop
Summary: new check idea: avoid using Q_FOREACH to iterate over QMap/QHash keys and ret...
Status: RESOLVED FIXED
Alias: None
Product: clazy
Classification: Developer tools
Component: general (show other bugs)
Version: unspecified
Platform: Other Linux
: NOR wishlist
Target Milestone: ---
Assignee: Sergio Martins
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2016-02-12 09:37 UTC by Nyall Dawson
Modified: 2016-02-15 19:07 UTC (History)
1 user (show)

See Also:
Latest Commit:
Version Fixed In:
Sentry Crash Report:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
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