In this article Goodbye, Q_FOREACH from KDAB, they warn that a range-based for
could cause a detach of a Qt container.
See also here : Using C++11 range-based for loop correctly in Qt
I understand that the for
will cause a detach because it is calling some non-const iterators if the container is not const.
Is it the same for the QHash::keys()
return value ?
The keys()
function is const so my map will not detach, but the return value is passed by value so will I copy the QList twice ?
Then, should I loop like this ?
for(auto key : qAsConst(map.keys())) {
// do something with key or map.value(key)
}
No, it does not even compile (Qt5.9 - MSVC 2015) :
QMap<QString, int> map;
for(auto key : qAsConst(map.keys())) {
// do something with key or map.value(key)
}
error: use of deleted function 'void qAsConst(const T&&) [with T = QList]'