Why is foreach iterating with a const reference?


I try to do the following:

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

Which looks like it should be legitimate but I end up with an error complaining that it cannot convert from 'const QString' to 'QString &'.

Why is the Qt foreach iterating with a const reference?

8/24/2017 1:26:29 PM

As explained on the 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.

It makes a copy because you might want to remove an item from the list or add items while you are looping for example. The downside is that your use case will not work. You will have to iterate over the list instead:

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

A little more typing, but not too much more.

10/21/2009 3:00:18 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow