[Development] The future of smart pointers in Qt API
volker.hilsheimer at qt.io
Fri Jan 31 16:33:14 CET 2020
> On 31 Jan 2020, at 16:27, Vitaly Fanaskov <vitaly.fanaskov at qt.io> wrote:
> On 1/31/20 4:13 PM, Eric Lemanisser wrote:
>>> > I would like to separate pointers with simple ownership and complicated > ownership. We could solve passing of raw pointers with simple ownership > first using standard smart pointers. Where as the more complicated pointers > would require special classes like those Daniel Teske has been working on. I'm not sure how to properly identify what is the "complicated ownership". I don't think that there are places in Qt API where we really need something more complicated than regular shared/weak/unique pointers. Even intrusive pointers are not required I guess. When you think about something more complicated, this is probably an architectural problem (like with parent-child) or bad API design. Can you provide some real examples where we need something more complicated than regular smart pointers, please?
>> Are we really considering abandoning the parent-child ownership for
>> qt6 ? that would be a huge breaking change
> Not abandoning, I think, but re-implementing properly. Raw pointers
> cause some certain problems here and changing them to something more
> smart would be nice. But it doesn't mean that we should get rid of
> parent-child model entirely. The point is that we can make it more
> explicit just by using smart pointers.
> To make it clear, there is no decision made. We're just discussing.
Parent-child relationship is not going to go away, it has purpose beyond object lifetime: the visual hierarchy is encoded in the parent/child relationship of widgets, for example.
Making ownership of objects, and assumptions regarding their life-cycle, explicit in code is a good thing though. Using smart pointers is the idiomatic C++ way to do so. But it doens’t have to be the only way; a call to QObject::setParent is IMHO just as explicit, and parent/child in Qt is a concept you have to learn either way.
But sometimes our APIs are messy. QTabWidget::addTab transfers ownership of the QWidget*; QTabWidget::addAction does not transfer ownership of the QAction*. Unless you understand fairly well how QAction works, or unless you read/remember the documentation, it’s impossible to see from the code what happens wrt to object ownership.
API naming is not a scalable way to make the distinction, so finding how we can use smart pointers to make it clear in the code when ownership is transferred is a good idea.
Perhaps the pragmatic approach is to address this in those APIs that take a QObject* but don’t transfer ownership. I believe those are much fewer. Otherwise, the convention can be that any API that takes a raw pointer takes ownership. How this is implemented internally doesn’t matter.
More information about the Development