Search code examples
c++qtdeep-copyqtcoreqlist

How would a QList containing pointers behave when passed by value


Suppose you have QList containing pointers QList<SomeThingCool*> and you pass it to a method with a signature void doCoolStuff(QList<SomeThingCool*> list) what would the space and time implications be of such a call?

My guess is that there will be some overhead because a copy will be created of the QList object, we however do not need to do a deep copy since we are dealing with pointers.

One difference in behaviour would be that if doCoolStuff makes modifications to the list, the original list will remain untouched.


Solution

  • What you are writing is correct for generic C++, however QList, among some other Qt classes, is a bit special when it comes to this. It is implicitly shared a class, aka. copy-on-write (COW). What does that mean, yeah?

    The only addition to your explanation is that if you do not intend to modify the list inside the body of the method or function, your list be implicit shared, which means a shared data pointer will be only the extra space constraint.

    If you intend to modify the list inside the function or method body, then there will be a deep copy made for the list. Naturally, your pointers will still remain shallowly copied because they are pointers.

    As for the time dimension, by implicitly using this technique for this class, you spare the time spent on copying the list if you do not do any modification.