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

Bo Thorsen bo at vikingsoft.eu
Thu May 5 09:18:31 CEST 2016


Den 04-05-2016 kl. 16:48 skrev Nikos Chantziaras:
> 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?

I'm still not sure if I should respond to this or not. You're clearly 
trying to solve an unsolvable problem.

This mail is going to sound like a rant, because I've heard those types 
of arguments from Qt newbies again and again. But it's actually not. 
There's information here that will lead you to a code style that fits 
the Qt memory model. Not your memory model.

First, you need to listen to this and fully understand it: There is *no* 
way you can code C++ so memory errors are impossible.

Using smart pointers is just a silly pipe dream of the nineties that 
unfortunately hasn't gone away. As Herb Sutter (I think, not completely 
sure) once said: "Smart pointers is a solution in search of a problem".

Smart pointers is good for one thing only: To delete objects that 
control their own life span.

For all other - and that's 99.9% - objects, it's cleaner simpler and 
more efficient if you get rid of the notion that a system can do it for 
you, and start giving clear lifetime ownership of your objects.

Yes, you can get crashes or memory loss. That's why you don't hire crap 
coders to do C++, and check your code with tools like valgrind.

I'm sure you will have a long list of objections as to why I'm 
completely wrong. Shared pointer lovers usually do. I don't care. I've 
been doing Qt coding for 20 years and have tried every trick available 
and come to the conclusion that it's actually only up to me writing good 
code.

I hope this helps. I give the same type of arguments to my customers. 
The smart ones get it, the others pay with increased maintenance cost 
over the years.

Bo Thorsen,
Director, Viking Software.

-- 
Viking Software
Qt and C++ developers for hire
http://www.vikingsoft.eu



More information about the Interest mailing list