Search code examples
c++qtcopy-on-writeqshareddata

Is 'implicit sharing' heritable from Qt classes?


If I create a subclass of an implicitly shared Qt class (e.g., QList), will my subclass be implicitly shared as well?

I read the brief introduction to implicit sharing located in the QtCore5.3 documentation, but I didn't see any mention of heritability.

My purpose in asking is to try to write more efficient code when deciding which arguments to pass and how to pass them.


Solution

  • As said in the comments, the Qt classes using implicit-sharing are usually data-containers or tools and are not intended to be subclassed.
    You can notice that because there is no virtual destructor, actually no virtual function at all.

    Because of the risks and bad practice, you probably want to make a different design without inheritance.


    To answer your question :

    How implicit-sharing works ?
    The class instances share the data and explicitly tell when they need to modify this data (and thus, deep-copy it) by calling a detach() function.
    So the motherclass data would still be a shared data-pointer, and the motherclass methods would still detach at appropriate time. But your subclass data members would not be implicitly-shared and your subclass methods would not implicitly detach when it might be needed.
    You might also overload methods and forget to detach, and so mess up the shared data.

    You do not benefit of the implicit sharing, you have to explicitly set it again for your own data.
    You will need to encapsulate the data in a shared-data container, and manage the detach in your methods. Check the doc :
    http://doc.qt.io/qt-5/qshareddatapointer.html#details