[Development] The future of smart pointers in Qt API

Ulf Hermann ulf.hermann at qt.io
Wed Feb 5 09:33:56 CET 2020


> A "Qt style" "RAII handle" is a QObject parent at creation time.
> There is no double deletion in this context, *only* when you start
> to sprinkle in other ownership models, i.e. deviate from "Qt style".

No.

There are many places in our API that expect or return plain QObject 
pointers and you just have to know whether those are or should be 
pre-owned by something and whether ownership is transferred by calling 
the method. In quite many places it's advisable to store a QObject 
pointer in a QScopedPointer or std::unique_ptr in order not to leak it 
under adverse conditions.

In some places you're expected to pass an unowned object to a method, 
for example when adding a widget to a layout. Most getters on widgets 
and similar, just return pre-owned objects you should _not_ put into a 
smart pointer (which would indeed risk double-deletion) or re-parent. 
But then, there are also factory methods that create an unowned object 
you should definitely re-parent or put into a smart pointer, and there 
are methods like the whole QVariant/QObject interaction that expect you 
to _keep_ ownership of the objects you pass and that return objects 
supposedly owned by something else, that you should _not_ put into a 
smart pointer or reparent.

A prime example of problems arising from the ambiguity of plain pointers 
are all the qtdeclarative tests that currently leak the result of 
QQmlComponent::create(). Those are quite a headache when I'm trying to 
get meaningful results from ASAN.

I would very much appreciate a way to denote the ownership conditions 
when transferring a pointer on a language level. That is basically what 
smart pointers are.

Ulf


More information about the Development mailing list