[Interest] What's the recommended way to put QObjects in smart pointers?
Sean Harmer
sean.harmer at kdab.com
Wed May 4 17:00:07 CEST 2016
On Wednesday 04 May 2016 17:48:50 Nikos Chantziaras wrote:
> 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?
>
> Or, to phrase it in another way, is there a way to eliminate the 'new'
> keyword completely from my code-base when using QObjects with a parent?
Use smart pointers to only manage the root objects of your QObject hierarchies
and rely upon QObject to manage the child objects.
Cheers,
Sean
--
Dr Sean Harmer | sean.harmer at kdab.com | Managing Director UK
KDAB (UK) Ltd, a KDAB Group company
Tel. +44 (0)1625 809908; Sweden (HQ) +46-563-540090
Mobile: +44 (0)7545 140604
KDAB - Qt Experts
More information about the Interest
mailing list