Why is foreach iterating with a const reference?

后端 未结 5 1207
生来不讨喜
生来不讨喜 2021-02-19 18:59

I try to do the following:

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

Which looks like it should be legitimate but

相关标签:
5条回答
  • 2021-02-19 19:06

    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.

    0 讨论(0)
  • 2021-02-19 19:18

    Maybe for your case:

    namespace bl = boost::lambda;
    std::for_each(a.begin(),a.end(),bl::_1 += "s");
    
    0 讨论(0)
  • 2021-02-19 19:21

    or you can use

    QList<QString> a;
    BOOST_FOREACH(QString& s, a)
    {
       s += "s";
    }
    
    0 讨论(0)
  • 2021-02-19 19:24

    I believe Qt's foreach takes a temporary copy of the original collection before iterating over it, therefore it wouldn't make any sense to have a non-const reference as modifying the temporary copy it would have no effect.

    0 讨论(0)
  • 2021-02-19 19:30

    With C++11, Qt now encourages this standard for syntax instead of Qt foreach :

    QList<QString> a;
    for(auto& s : a)
    {
        s += "s";
    }
    
    0 讨论(0)
提交回复
热议问题