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

Nikos Chantziaras realnc at gmail.com
Wed May 4 16:48:50 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?

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?




More information about the Interest mailing list