QList and QSharedData

  • Hi all,

    I'm currently reading the QList description and there's something I'm not sure about. It says :

    bq. or if T is one of Qt's shared classes, then QList<T> stores the items directly in the pointer array.

    Does it mean only the classes listed in QT's shared classes will be stored as pointer when passed as value or any classes derived from QSharedData will also be stored in the pointer array, and not on the heap.

    Example :

    @// class SomeClass : public QSharedData

    void addClassToList (SomeClass & someClass) {

    // and we use like this
    SomeClass *unimaginativelyNamedClass = new SomeClass();
    addClassToList (*unimaginativelyNamedClass);

    with this code, for what I think (and hope) is gonna happen is:

    unimaginativelyNamedClass is allocated with memory from the heap. The refcount of QSharedData is 0.

    when added to m_myQlist, the heap address of the class (this) is stored in the pointer array of the list, and the refcount = 1.

    When the list is deleted, the refcount falls to 0 and the heap memory is released.

    Am I right ?


  • And the answer is : NO!

    I'm gonna answer why, because every question in a forum should be answered for future references, but its a little technical (but not much).

    First, I found the description of a shared class on the page Implicit Sharing :

    bq. A shared class consists of a pointer to a shared data block that contains a reference count and the data.

    So a shared class is the size of a pointer, which match the Qlist description :

    bq. If T is itself a pointer type or a basic type that is no larger than a pointer, or if T is one of Qt's shared classes, then QList<T> stores the items directly in the pointer array.

    So i went through QT's sources and enlighted myself about the size of classes and I found this on google :

    bq. Size of a class object is nothing but it's non-static member data + if it has any virtual functions, then it's _vptr size + it's inherited data, if it is inherited from some class.

    So a shared class contains a single member (a pointer to its data struct or class) and many function members. The data struct contains a refcount and the data of the class. And that's exactly how QString (a shared class) is coded.

    So having used a QList of pointers in the first place would have been a lot less trouble, but learning such technical stuff is just way too awesome.


Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.