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

Nikos Chantziaras realnc at gmail.com
Wed May 11 21:56:48 CEST 2016


On 10/05/16 23:47, Alejandro Exojo wrote:
> El Thursday 05 May 2016, Nikos Chantziaras escribió:
>> Well, basically what I want is not having even a single 'new' or
>> 'delete' anywhere in my code. I already achieved that with all my non-Qt
>> projects.
>>
>> By now, I consider application-level code that uses 'new' or 'delete' as
>> bogus and in need of fixing.
>
> I think you are confusing the path to arrive to some place, with the place
> itself. make_shared and make_unique hide the "new", but their main reason to
> exist is that some classes willingly throw on construction. That's not the
> case of Qt classes, so using new on them is fine.

My own classes do, so using new is not fine.


> There are things like
> ScopeGuard, or other "RAII" classes which are not a smart pointer, so they
> might not hide the "new", but are exactly as correct as your code without it.

This results in code duplication, since you write the same cleanup code 
everywhere.


> Note that classes like QRunnable or QAbstractAnimation can delete themselves
> when done. Nothing stops you to create a QDialog subclass that deletes itself
> after you've got the result of exec() if you prefer that. It would be even
> easier to spot problems, and with less "extreme" requirements on the C++
> support of the compiler, IMHO.

The easiest solution is to just have a smart pointer auto-delete it. 
Cannot get any simpler than that.




More information about the Interest mailing list