ymoreau
ymoreau

Reputation: 4016

Should I use qAsConst on QHash::keys() in a C++11 range-based for

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)
}

Upvotes: 5

Views: 5590

Answers (2)

David Faure
David Faure

Reputation: 1997

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

Upvotes: 3

ymoreau
ymoreau

Reputation: 4016

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

Upvotes: 3

Related Questions