4

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)
}
ymoreau
  • 3,402
  • 1
  • 22
  • 60

2 Answers2

3

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]'

ymoreau
  • 3,402
  • 1
  • 22
  • 60
  • The function is deleted for rvalue due to (possible) ownership issues. As stated in the article you can simple assign the rvalue to a const variable i.e. `auto const keys = map.keys()` and then use that in the range for. – BaCaRoZzo Nov 06 '18 at 08:11
3

Creating a temporary keys() container just to iterate over it, is a really slow solution anyway. Prefer using iterators instead.

David Faure
  • 1,836
  • 15
  • 19