[Development] unique_ptr and Qt, Take 2

Matthew Woehlke mwoehlke.floss at gmail.com
Wed Jun 12 23:11:04 CEST 2019


On 03/05/2019 15.13, Thiago Macieira wrote:
> On Friday, 3 May 2019 12:04:40 PDT Giuseppe D'Angelo via Development wrote:
>> Anyhow, I too feel that we may need a dedicated smart pointer class for
>> this, to catch all the corner cases and allow the existing flow of
>>
>> 1) create something
>> 2) (re)parent it
>> 3) keep using that something via a non-owning pointer.

Or... just don't do that?

I can't recall that I've *ever* had problems with QObject ownership.
Generally, if you follow three rules:

- If you create an object on the stack, either don't parent it or ensure
its parent outlives it. (Usually not hard!)
- If you create an object with `new`, **create** it with a parent.
- Otherwise use a smart pointer (QScopedPointer or QSharedPointer)¹.

...you just won't have problems.

(¹ These days, you can also add "or STL equivalents".)

> Same here. I think Daniel is on to something and we really should explore 
> having smart pointers in Qt 6, but at this point I'm not convinced 
> std::unique_ptr alone is it. I'd like to see what we could achieve with a 
> QObject-specific smart pointer that understood ownership-taking functions 
> (setParent, addWidget, etc.) and observing-only API (like connect()).

Idea: make this hypothetical pointer be a QObject that initially "owns"
the object to which it points. If the object is reparented, the pointer
will stop "owning" it but will still have the reference.

(Not an optimal implementation, but could be easily implemented as a
proof of concept.)

-- 
Matthew


More information about the Development mailing list