Reputation: 19305
I am getting confused about the QList copy constructor by the documentation.
QList::QList ( const QList & other ) Constructs a copy of other.
This operation takes constant time, because QList is implicitly shared. This makes returning a QList from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), and that takes linear time.
Then on the link about being implicitly shared, it talks about reference counting and copy-on-write. Is this a deep copy or just a shallow copy?
Upvotes: 8
Views: 7499
Reputation: 4274
It's a shallow copy. A deep copy of the data happens behind the scenes the first time you call a non-const function on the copy or the original list.
Upvotes: 6
Reputation: 2761
This operation takes constant time, because QList is implicitly shared.
If you don't modify the list, those are shared ! So Behind the scene, you read at the same address the informations !
If a shared instance is modified, it will be copied (copy-on-write), and that takes linear time.
But if you modify the copy list, there is no other choice that copy effectively the list ! And so, you have a linear cost depending on the list size.
from qt doc on copy on write and shared memory :
A deep copy implies duplicating an object. A shallow copy is a reference copy, i.e. just a pointer to a shared data block. Making a deep copy can be expensive in terms of memory and CPU. Making a shallow copy is very fast, because it only involves setting a pointer and incrementing the reference count.
So if you don't modify the list you read the information at the same address that the list given as parameter, it's called shallow copy. And if you modify it, you will have a deep copy of the list.
Upvotes: 3
Reputation: 11808
The copy constructor does a fast (shallow) copy. If you then modify either the original list, or it's copy, a deep copy of the data will be made.
If you're in any doubt, I suggest you re-read the documetnation on copy-on-write semantics.
This is the same behaviour as QString, QList, QArray, and many other Qt classes.
Upvotes: 2
Reputation: 14341
AFAIK, when copying the content (on write), it calls the copy constructor of each element in the list, like in the case of std::list.
Upvotes: -2