tags:

views:

925

answers:

4

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?

A: 

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.

Cătălin Pitiș
+4  A: 

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.

Intransigent Parsnip
...or on the original list! Basically, any time the list data would be changed, a deep copy is created.
Thomi
Oh, of course! Thanks, I edited my answer to avoid confusion to those who don't read comments.
Intransigent Parsnip
Just would like to follow up that I made a mistake - if you hold a QList or QVector of pointers, don't expect the default deep copy constructor to help you to make new instances of what those pointers point to...
Extrakun
+1  A: 

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.

Matthieu
+1  A: 

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.

Thomi