How to fix foreach warning: allocating an unneeded temporary container [-Wclazy-container-anti-pattern]
-
I am getting lot of these warning for this code:
foreach (QString key, target->PropertyBag.keys()) // this is where I see it { if (!this->PropertyBag.contains(key)) this->PropertyBag.insert(key, target->PropertyBag[key]); else this->PropertyBag[key] = target->PropertyBag[key]; }How should I change it so that I don't see the warning? Saving a list of keys in QList would probably dismiss the warning as well but it would also create a temporary container.
-
No point in calling same method again and again. Try the following.
QList keys = target->PropertyBag.keys();
foreach (QString key, keys){ } -
also in my case PropertyBag is in most cases an empty hash, so I am thinking that maybe putting if (!PropertyBag.isEmpty()) in front would avoid unnecessary copy of empty qhash? This code is called in a loop for large amount of items, each item has its own PropertyBag.
-
I am getting lot of these warning for this code:
foreach (QString key, target->PropertyBag.keys()) // this is where I see it { if (!this->PropertyBag.contains(key)) this->PropertyBag.insert(key, target->PropertyBag[key]); else this->PropertyBag[key] = target->PropertyBag[key]; }How should I change it so that I don't see the warning? Saving a list of keys in QList would probably dismiss the warning as well but it would also create a temporary container.
for (auto & element : qAsConst(target->propertyBag)) PropertyBag.insert(key, element.first);foreachis deprecated.