Bug? Memory leak with QVariantList containing allocated QObjects

  • I am having a method returning a QVariantList containing allocated pointers. I tried the 'scoped pointers' however the compiler does not allow them to be converted to variants. Here is an example of the code:

    [code]class CMyObject : public QObject
    QString m_sTitle;
    QString m_sDescription;

    QVariantList oList;
    oList.append(QVariant::fromValue(new CMyObject));
    oList.append(QVariant::fromValue(new CMyObject));
    return QVariant::fromValue(oList);

    The list is accessible in JavaScript within the browser, however the destructor of CMyObject is never called. The challenge is I have to dynamically generate the list, because the list is like a 'query' and each time a different list is returned.

    I would like to know how can I return a list of objects and have Qt WebKit delete the objects when the variable goes out of scope.

  • Hi,

    I understand you have a memory leak. I my opinion, and according to the documentation, the arg of Q:Variant::fromValue is cont T &.
    it means, You give it an object (a pointer in reality) and QVariant is going to duplicate it.

    Try something like this :
    @CMyObject cMyObject;


  • Thank you for your reply. I tried your solution and it crashes. This is because the object allocated on the stack is destroyed, and therefore JavaScript refers to a dangling pointer.

    The QVariant does not duplicate the object (it does not know how). I wrote a ticket to Digia for a QObjectShared with a reference counter, similar as IUnknown and IDispatch are implemented.

  • Lifetime Qt Champion


    QObject can't be copied and being copyable is mandatory for custom types to be used in a QVariant. QVariant::fromValue returns a variant containing a copy of the object passed.

  • Is there a macro I need to specify for the QObject to be copied? If the QObject is copied, then I should see extra calls in its constructor and destructor.... right?

  • Lifetime Qt Champion

    No there's not, "here":http://qt-project.org/doc/qt-5/qobject.html#no-copy-constructor-or-assignment-operator is the explanation about the copy restriction. In the case of QObject you can only use a pointer so it's the pointer that is copied not the object

  • This is what I understood. What I need is a mechanism, typically a reference counter, to know when the variable in JavaScript goes out of scope. If there was a QObjectShared with a built-in reference counter, then the [virtual] destructor ~QObjectShared would indicate the object is out of scope.

  • Have you looked at QSharedPointer? Reference counting is built in.

  • Have you looked at QSharedPointer? Reference counting is built in.

Log in to reply

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