[Development] The future of smart pointers in Qt API

Ola Røer Thorsen ola at silentwings.no
Mon Feb 3 10:26:41 CET 2020


søn. 2. feb. 2020 kl. 00:15 skrev Giuseppe D'Angelo via Development <
development at qt-project.org>:

> If we're going for this logical fallacy, then let's up the ante: a
> unique pointer is just a shared pointer without copy semantics. Why not
> using shared pointers everywhere?
>
>
I'm not sure if I'm able to follow this discussion correctly (lost track of
what is sarcasm or irony or whatever), but I'd just like to add some
thoughts:

- As a long-time Qt user I don't feel that the current QObject parent/child
model is a problem that needs fixing. It works well and is not what keeps
me from getting things done. I'd be worried if I would have to re-write
lots of existing code and re-think the memory management if I was to
upgrade to Qt 6. At work we might just stay with 5.15 for a long while, and
then reconsider Qt6 or some other solution for the next product. Please try
to keep Qt 6 as source-compatible as possible.

- shared_ptr is not just unique_ptr without copy semantics. It has lots of
nice use cases, but should not be used everywhere without any good reason.
It introduces atomic reference counting stored somewhere else in memory,
and has an additional performance cost. There is no clear definition of
what owns the object anymore, and less control of when an object is deleted
(so for example no control of in which thread the destructor might be
called). It can cause memory leaks due to circular references.

- I like unique_ptr and would be happy to use it where it makes sense, like
when being given the ownership of an object from some Qt function.

- We use QObject::deleteLater() a lot, deleting QObjects directly seems to
trigger rare bugs/crashes when sharing them with qml.

- The biggest struggle I have with Qt currently regarding pointers is when
you share a dynamic model of QObject* to qml. Here it would actually be
useful to have shared_ptr, and I've solved this with some Q_GADGET-based
wrappers. (One could argue I should not share QObject* stuff in a model,
but putting everything in model roles does not scale well when the objects
have properties that change often, or have properties to other objects.
Hard to maintain, redundant code, no error handling in qml if a role is
mistyped, and QVariant's performance is not good.)

Cheers,
Ola
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20200203/3377fadd/attachment.html>


More information about the Development mailing list