Qt的文档说明如下:
Thanks to implicit sharing,it is very inexpensive for a function to return a container per value. The Qt API contains dozens of functions that return a QList or QStringList per value (e.g.,QSplitter::sizes()). If you want to iterate over these using an STL iterator,you should always take a copy of the container and iterate over the copy. For example:
// RIGHT const QList<int> sizes = splitter->sizes(); QList<int>::const_iterator i; for (i = sizes.begin(); i != sizes.end(); ++i) ... // WRONG QList<int>::const_iterator i; for (i = splitter->sizes().begin(); i != splitter->sizes().end(); ++i) ...
解决方法
对splitter-> sizes()的两个调用产生容器的两个不同副本.由于begin()来自一个和另一个end(),它们不会形成一个有效的范围.然后,循环将从第一个容器的末端走出,进入未定义行为的土地.
基于范围的循环可以正常工作:for(int size:splitter-> sizes()){…}