Use of deleted function error with qAsConst

293 Views Asked by At

I'm writing a simply loop which iterates through the keys in a QMap as show below:

  for (const auto &id: qAsConst(m_myMap.keys())) {
    // Do something which does not affect m_myMap
  }

Compiling the loop generates an error:

use of deleted function 'void qAsConst(const T&&)[with T=QList]'

Without the qAsConst I get the error:

Allocating an unneeded temporary container.

I thought the whole point of qAsConst was to avoid creating the temporary container. But I don' understand the message - why is it calling a deleted function? How do I fix this to get rid of the error / warning?

2

There are 2 best solutions below

5
273K On

It means that you create a container with this statement: m_myMap.keys() for no good reason. qAsConst() does not prevent the unneeded allocations. const T& QMap::const_iterator::operator*() const returns a value, the range-loop with keys cannot be used.

Use a usual loop like below

for (auto it = m_myMap.begin(); it != m_myMap.end(); ++i) {
  // it->key();
}

The first my answer is wrong.

for (const auto& [id, value]: m_myMap) {
  // Do something which does not affect m_myMap
}
0
hyde On

QMap::keys() returns a QList by value.

qAsConst can't be applied to this rvalue because its lifetime ends when qAsConst returns. This is why this is prevented on purpose, and you get that error about deleted function.

A solution is to use a temp variable:

const auto ids  = m_myMap.keys();
for (auto &id: ids) {
    ....

Now keys is const already, so const or qAsConst would be redundant, it's already so.


Note that using a const iterator would be more efficient, avoiding O(log n) QMap lookup every round.