c++ - 为什么 foreach 使用 const 引用进行迭代?

标签 c++ qt foreach

我尝试执行以下操作:

QList<QString> a;
foreach(QString& s, a)
{
    s += "s";
}

这看起来应该是合法的,但我最终遇到了一个错误,提示它 cannot convert from 'const QString' to 'QString &'

为什么 Qt foreach 使用 const 引用进行迭代?

最佳答案

Qt Generic Containers Documentation 中所述:

Qt automatically takes a copy of the container when it enters a foreach loop. If you modify the container as you are iterating, that won't affect the loop. (If you don't modify the container, the copy still takes place, but thanks to implicit sharing copying a container is very fast.) Similarly, declaring the variable to be a non-const reference, in order to modify the current item in the list will not work either.

它制作拷贝是因为您可能想从列表中删除一个项目或在循环时添加项目。缺点是您的用例将不起作用。您将不得不遍历列表:

for (QList<QString>::iterator i = a.begin(); i != a.end(); ++i) { 
  (*i) += "s";
} 

多打一点字,但不要太多。

关于c++ - 为什么 foreach 使用 const 引用进行迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1600928/

相关文章:

java - 在 java 增强的 for 循环中,假设要循环的表达式只被评估一次是否安全?

java - 错误 : incompatible types: unexpected return value : Java 8

c++ - setDIbitstodevice Turbo C++

c++ - 如何找到全局静态初始化

c++ - boost filtering_istream gzip_decompressor 未压缩文件大小

c++ - Ghostscript api 请求 "press <return> to continue"

foreach - 新旧 foreach 循环

c++ - 包含非平凡成员 union 的类的构造函数和复制构造函数

c++ - 关于C++指针的疑惑

qt - 如何使用 Yocto 项目正确配置 Qt SDK?