When does a deep copy happen to a QList?

徘徊边缘 提交于 2019-12-04 00:38:22

问题


In a class I'm working on, I am juggling several QLists. I have heard that Qt tries not to make deep copies of lists whenever possible. From what I understand, that means that no deep copy happens when you do this:

QList<int> myList;
myList << 1 << 2 << 3 << 4;
QList<int> otherList = myList;  // No deep copy

In some cases, I need to make sure a deep copy never happens to the QList. Exactly what kind of operation or action do I need to make sure to avoid in order to make sure a deep copy never happens to a QList I'm working with?


回答1:


QLists are implemented using implicit sharing.

Object assignment (with operator=()) for implicitly shared objects is implemented using shallow copies.

This means that assignment alone will never cause the contained data to be copied. However, writing to a shared instance will cause the source object to be copied. This pattern is commonly known as copy-on-write.

So, to answer your question, if you never write to shared instances then they will never be copied. If you want to completely prevent copies being made then derive from QList and override and hide the copy constructor and assignment operator.




回答2:


When you pass a QList as a argument of a function or when you create copies without modifying it Qt just pass a "wrapper", the real data is never copied along. Implicit sharing is the Qt implementation of the Flyweight pattern, see here.




回答3:


Just make sure to use constBegin(), constEnd(), pass by const reference, don't modify or copy.



来源:https://stackoverflow.com/questions/6866183/when-does-a-deep-copy-happen-to-a-qlist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!