for(const QJsonValue& v1 : root.toArray())

在遍历QJsonArray时,软件提示
c++11 range-loop might detach Qt container (QJsonArray)

原因,QJsonArray有两个枚举器,如下所示
inline iterator begin() { detach(); return iterator(this, 0); }
inline const_iterator begin() const { return const_iterator(this, 0); }

除非要修改枚举的内容,否则大部分情况下应该用第二个枚举器。
因为QT里大部分容器使用了隐性共享,用第一个枚举器时会调用detach复制容器的内容,导致性能降低。
如何能避免使用第一个枚举器?解决办法是把QJsonArray变成常量,这样就强制使用第二个枚举器。
const QJsonArray& root2 = root;  再遍历root,或者在遍历时使用 qAsConst(root)

posted on 2023-05-27 20:42  五星  阅读(1205)  评论(0编辑  收藏  举报