Use of deleted function error with qAsConst

huangapple go评论92阅读模式
英文:

Use of deleted function error with qAsConst

问题

我正在编写一个简单的循环,它遍历了一个 QMap 中的键,如下所示:

for (const auto &id : qAsConst(m_myMap.keys())) {
    // 做一些不影响 m_myMap 的操作
}

编译这个循环会生成一个错误:

使用已删除的函数 'void qAsConst(const T&&)[with T=QList]'

如果没有使用 qAsConst,我会得到以下错误:

分配了不需要的临时容器。

我以为使用 qAsConst 的整个目的是避免创建临时容器。但我不理解这个错误信息 - 为什么它会调用一个已删除的函数?我该如何修复这个错误/警告?

英文:

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

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?

答案1

得分: 2

这意味着您出于毫无理由的情况下创建了一个容器,使用此语句:m_myMap.keys()qAsConst()并不能防止不必要的分配。const T&amp; QMap::const_iterator::operator*() const返回一个值,无法使用带键的范围循环。

请使用以下通常的循环方式:

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

第一个答案是错误的。

for (const auto&amp; [id, value]: m_myMap) {
  // 执行一些不影响 m_myMap 的操作
}
英文:

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&amp; 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-&gt;key();
}

The first my answer is wrong.

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

答案2

得分: 2

QMap::keys() 返回一个 QList,按值传递。

qAsConst 不能应用于这个右值,因为它的生命周期在 qAsConst 返回时结束。这是故意阻止的,所以你会得到有关已删除函数的错误。

一个解决方案是使用一个临时变量:

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

现在 keys 已经是 const,所以 constqAsConst 都是多余的,它已经是这样了。


请注意,使用 const 迭代器会更高效,避免每轮都进行 O(log n) 的 QMap 查找。

英文:

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 &amp;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.

huangapple
  • 本文由 发表于 2023年6月15日 04:50:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477444.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定