How to avoid Clazy warning "Allocating an unneeded temporary container" when joining keys?
-
For some message I need a list of
QMapkeys as a string. How can following (simplified) code be improved to avoid said Clazy warning?const QMap<QString, int> shoppingList {{"Bananas", 5}, {"Bread", 1}, {"Milk", 2}}; QString keysText = shoppingList.keys().join(", "); -
For some message I need a list of
QMapkeys as a string. How can following (simplified) code be improved to avoid said Clazy warning?const QMap<QString, int> shoppingList {{"Bananas", 5}, {"Bread", 1}, {"Milk", 2}}; QString keysText = shoppingList.keys().join(", ");@Jens-G
I think it does not like you generatingkeys()and then iterating it tojoin(). I think it would like you to write something like:for (const auto & element : shoppingList ) keysText += ...or use QMap::key_iterator QMap::keyBegin() const or similar iterator.
Though how that is as convenient as being able to use
join(", ")I don't know/see! Unless an expert knows better. Sounds to me like you/we may know better than clazy here :) [Oh, unless you are using a million+ keys, then this is good advice :) ] -
For some message I need a list of
QMapkeys as a string. How can following (simplified) code be improved to avoid said Clazy warning?const QMap<QString, int> shoppingList {{"Bananas", 5}, {"Bread", 1}, {"Milk", 2}}; QString keysText = shoppingList.keys().join(", ");@Jens-G As @JonB already said clazy complains about the temporary QList returned by
.keys().
To prevent it you could either useQMapIteratororQMap::key_iteratorto join your code.
I made some quick and dirty "performance" measurements on my machine and STL-style key iterators seem to be consistently faster than the other methods:.join(): T1: "Bananas, Bread, Milk" Timing: 3900 nanoseconds. QMapIterator: T2: "Bananas, Bread, Milk" Timing: 4200 nanoseconds. STL-style: T3: "Bananas, Bread, Milk" Timing: 1500 nanoseconds.Done on Windows 11, Visual C++ 2022, Qt 6.5.0 Release mode with AVX2