'for' loop vs Qt's 'foreach' in C++

前端 未结 11 860
我寻月下人不归
我寻月下人不归 2020-12-14 05:28

Which is better (or faster), a C++ for loop or the foreach operator provided by Qt? For example, the following condition

QList

        
11条回答
  •  佛祖请我去吃肉
    2020-12-14 06:13

    I don't want to answer the question which is faster, but I do want to say which is better.

    The biggest problem with Qt's foreach is the fact that it takes a copy of your container before iterating over it. You could say 'this doesn't matter because Qt classes are refcounted' but because a copy is used you don't actually change your original container at all.

    In summary, Qt's foreach can only be used for read-only loops and thus should be avoided. Qt will happily let you write a foreach loop which you think will update/modify your container but in the end all changes are thrown away.

提交回复
热议问题