[Development] parented_ptr

André Somers andre at familiesomers.nl
Thu Oct 16 11:42:37 CEST 2025


Hi,

On 15-10-2025 16:30, Daniel Schürmann wrote:
> Hello
>
> My name is Daniel Schürmann and I am one of the core members in the 
> Mixxx team. We develop the QT based FOSS DJ software Mixxx.
>
> Since a couple of years we use a custom smart pointer to wrap pointers 
> to QObjects, where the lifetime is managed by the QT object tree.
>
> This is very useful for two reasons:
> * In reviews it is clear that there is no explicit delete required, it 
> eliminates the nowadays exceptional case of new() without delete().
> * The pointer asserts that the object has actually a parent and is not 
> leaked.
>
> It has proven to be useful and disappointing that it is not available 
> in all my QT projects. That's why I like to discuss to put it or 
> anything similar into the QT source itself.
>
> I have provided some more details in a QT bug here:
> https://bugreports.qt.io/browse/QTBUG-141134
>
> What do you think?
>
I have seen similar approaches in customer code before, but I don't 
quite see what parented_ptr itself brings to the table here?

You can work around the "no naked new()" rule by creating a custom 
template function that creates the type explicitly and enforces a 
non-null parent. I don't understand why you need a new pointer type for 
that. And for monitoring the validity of pointers to QObjects, we 
already have QPointer.

As the "naked pointer" way of working is ingrained quite deeply into Qt, 
I don't quite see how you expect this to find a place in the current API 
either?

Perhaps it might be easier or better to add a make_child template method 
to QObject that returns a new instance of the template type, parented to 
the object you call it on? So you could do something like:

auto button = myDialog->make_child<QPushButton>(tr("Some button"));

instead of

auto button = new QPushButton(tr("Some button"), myDialog);

I think it should be possible to specialize these where needed (like in 
this case, where the expected parent is actually a QWidget, not a 
QObject), but I didn't try.

Cheers,

André




More information about the Development mailing list