[Development] unique_ptr and Qt, Take 2

Daniel Teske qt at squorn.de
Fri Jun 21 15:16:49 CEST 2019


>> The minor problem being that to not so small audiences,
>> new Whoosh(something);
>> just looks like a bug, and then you need to look three times to
>> realize that something is a parent.
> Sure... but `something.createChild<Whoosh>()` can help with that.
>
> OTOH, I just realized a problem with that... when the new child needs to
> take its parent in the ctor for other reasons. I don't know if there is
> an easy solution to that. (Of course, you can still pass the parent with
> createChild, but then you've violated DRY.)

There are multiple different implementations of createChild.

The one I did choose requires the class to have a tagged ctor, meaning a 
ctor whose first parameter is QParentPtr<QWidget *> parent, so the ctor 
still has access to the actual parent ptr, and createChild simply passes 
the this pointer as the first parameter.

The drawback is obviously that requires new ctors, but there are several 
benefits:

* It is easier to do than having a later reparenting. Writing the new 
ctors is trivial.
* It allows for designing classes that can only created with a parent
* The cost of creating new ctors is only for those that want to make use 
of createChild.
* The new ctors have clear ownership semantics

In that patch, I've also added new ctors that take no parent ptr, to be 
used with make_unique or for stack-allocation.

And the last puzzle piece is that the qt users can choose to deprecate 
the old existing ctors, thus users can choose between:

* Keep just using Qt as is
* Make use of createChild by providing new ctors
* Ensure that each memory allocation is either parented or held in a 
unique_ptr, by opting into the deprecation + using some kind of code 
analysis preventing usage of raw news.

And obviously that's also the way, a existing code base could be 
transitioned.

The actual implementation of that mechanism is in:

https://codereview.qt-project.org/c/qt/qtbase/+/260618/1/src/corelib/global/qglobal.h 

https://codereview.qt-project.org/c/qt/qtbase/+/260618/1/src/corelib/kernel/qobjectdefs.h 


daniel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20190621/65fa2681/attachment.html>


More information about the Development mailing list