[Interest] What's the recommended way to put QObjects in smart pointers?

Nye kshegunov at gmail.com
Thu May 5 00:44:42 CEST 2016


> From what I can tell, QPointer does not delete the object, so that's a no
go.

No one said it does. Perhaps I'm misunderstanding, are you searching for a
silver bullet for memory management?

> Putting the objects on the stack doesn't work either, because the Qt
object model does not support that (it will call 'delete' on the object
even if it's on the stack.)

It will call delete because it can't know what's created in the heap and
what's not, but Qt's object model supports stack allocations just fine!
As long as you put the objects in ... drumroll ... a stack (i.e. FILO). So
the following will compile and run as a charm:

QObject parent;
QObject child(&parent);

And it applies to any class that has members:

class B : public QObject
{
    // ...
}

class A : public QObject
{
    A()
        : b(this) //< This is working perfectly, and has been for a decade
or so
    {
    }

    B b;
};

> That's not good enough. I need to delete objects way before their parent
is deleted.

So delete them. As I said, parent is notified of the child's deletion.

>> Assuming the above is one function, you could just do:

>> auto dialog = QDialog(parent);
>> //work

>> //end of scope, dialog gets deleted

> When 'parent' gets deleted before 'dialog', then 'dialog' gets deleted
even though it's on the stack.

And how does the parent gets deleted before the 'dialog' if I may ask,
unless you're doing deletions from different threads ...?





>
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> http://lists.qt-project.org/mailman/listinfo/interest
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20160505/cd2940c6/attachment.html>


More information about the Interest mailing list