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

Nye kshegunov at gmail.com
Wed May 4 18:09:15 CEST 2016


> I've been removing every trance of 'new' and 'delete' from my code and
> switching to something like:
>
>    auto obj = std::make_unique<Type>(ctor args);
>
> (Or std::make_shared, depending on the situation.)
>
> But for QObjects with a parent, that can go horribly wrong. So I have to
> do annoying stuff like:
>
>    auto dialog = new QDialog(parent);
>    // work...
>    delete dialog;
>
> Yes, 'parent' will eventually delete 'dialog', but that doesn't help
> much when 'parent' is a long lived object (like the main application
> window.)
>
> Is there a Qt-specific idiom where I can manage QObjects that have a
> parent with a smart pointer and not have to worry about double-deletion?

The parent will be notified of the child's deletion, so it's generally safe
to delete the child directly (with a few somewhat rare exceptions). So most
of the time QScopedPointer or it's STL equivalent work just fine. If you
need a guarded pointer for when Qt might delete the object while you still
hold a reference, you can use QPointer. I personally detest the unnecessary
new, and just create everything with auto storage where it's possible. So
that's another way you can eliminate new almost completely.

Kind regards.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20160504/cb33f4d9/attachment.html>


More information about the Interest mailing list