简体   繁体   English

将QList附加到QList <QList>

[英]Appending QList to QList<QList>

I have an interesting problem with Qt Qlist container. 我对Qt Qlist容器有一个有趣的问题。 Trying to append QList to QList makes my iterator to point to unknown part of memory. 尝试将QList附加到QList使我的迭代器指向未知的内存部分。

QList<int> listSmall;
QList<QList<int>> listBig;

for(int i = 0; i < 3; ++i)
    listSmall.append(i);

for(auto it = listSmall.begin(); it != listSmall.end(); ++it)
    listBig.append(listSmall);

Condition it != listSmall.end(); 条件it != listSmall.end(); always true if i append small list to big. 如果我将小名单附加到大名单上总是如此。 Why does this happen? 为什么会这样?

PS STL list works just fine. PS STL列表工作正常。

This is a known limitation of Qt containers when used with stl-like iterators. 当与类似stl的迭代器一起使用时,这是Qt容器的已知限制。 The documentation explains it. 文档解释了它。

Implicit sharing has another consequence on STL-style iterators: you should avoid copying a container while iterators are active on that container. 隐式共享对STL样式的迭代器有另一个影响:当迭代器在该容器上处于活动状态时,应避免复制容器。 The iterators point to an internal structure, and if you copy a container you should be very careful with your iterators. 迭代器指向内部结构,如果复制容器,则应该非常小心迭代器。

I am afraid you will have to find a different way of doing what you are trying to do (like using a standard list or iterate differently). 我担心你必须找到一种不同的方式来做你想做的事情(比如使用标准列表或以不同的方式迭代)。

TLDR: use cbegin() and cend() when you don't change values. TLDR:使用cbegin()cend()时,你不改变的值。

Details: 细节:

  • Compiler calls non-const begin() and end() version just as you asked; 编译器按照你的要求调用非const begin()end()版本; it can use const versions if you call cbegin() or begin() through const ref/pointer. 如果通过const ref / pointer调用cbegin()begin()它可以使用const版本。
  • QList tries to be copy-on-write and shares memory instead when you do listBig.append(listSmall); 当你执行listBig.append(listSmall);时,QList会尝试写入时复制并共享内存listBig.append(listSmall); .
  • On next iteration inside non-const end() there is call to detach() which copies data after confirming that local data is referenced more than once (like, it is referenced by listBig content already). 在非const end()内的下一次迭代中,调用detach() ,在确认本地数据被多次引用之后复制数据(例如,它已被listBig内容引用)。

All in all, that is a good example of why copy-on-write is hard to implement correctly. 总而言之,这是为什么难以正确实现copy-on-write的一个很好的例子。

BugReport with answer BugReport有答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM