[Development] The future of smart pointers in Qt API

Konstantin Shegunov kshegunov at gmail.com
Tue Feb 4 21:50:26 CET 2020


On Tue, Feb 4, 2020 at 8:55 PM Daniel Teske <qt at squorn.de> wrote:

> A QObject with a parent on the stack/unique_ptr is double owned and thus a
> problem. The severity of that problem is arguably worse with a unique_ptr.
>
Which is rather typical in well structured and valid threaded code, where
the children are stack allocated and are moved to the correct thread
whenever the parent is moved. There's more to memory management than
half-blindly throwing smart pointers at it, is my point. Say you substitute
all the private objects' allocations with std::unique_ptr, the question
would be what do you gain by that?

> Where my patch improves this situation is that the object ctors taking a
> parent ptr are all marked with a optional deprecation, thus if you opt into
> that, you'll get a warning for the second case even for the stack
> allocation.
>
I've looked at your patch the first time you posted it on the dev list, it
looked (and still does) fine to me.

> And yes this contrary to very crafty code that allocates objects in the
> right order on the stack, but that has never been the recommend way to use
> Qt.
>
The right order in the stack is given if the parent already contains the
children. And C++ is stack-based to begin with, otherwise people wouldn't
have invented stack objects managing heap-allocated data blocks (a.k.a
"smart pointers"). Even the idea of having free floating shared pointers
gives me shivers. I've run on more than one occasion into easy to miss
ownership pitfalls where I have had a slot executed on a QObject where the
object had already been deleted by a shared pointer. My current stance is
(in regards to the current state of affairs, that is) - don't use QObject
with shared pointers unless you like pain often and in copious amounts.
(nested event loops and/or queued events are what usually does it)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20200204/a6ef6a57/attachment-0001.html>


More information about the Development mailing list