[Development] The future of smart pointers in Qt API
Simon.Hausmann at qt.io
Fri Jan 31 20:08:21 CET 2020
On 31.01.20 11:07, Vitaly Fanaskov wrote:
> Hello everyone,
> We’ve been discussing for a while how Qt6 API can be improved with using
> smart pointers. Recently we came into some conclusions and want to
> discuss them with the community.
Thanks for taking the discussion here, Vitaly :)
> Smart pointers are for sure much better to use than raw pointers for
> many reasons. They manage lifetime automatically, show ownership
> semantic, and make code safer. It’s planned to officially recommend them
> to use in Qt6 API instead of raw pointers whenever this is possible. For
> sure, it should only be a choice for newly designed API.
> But how to use them in the API and which way is preferable is still
> unclear. There are two main options we have:
> 1) Use std::* smart pointers as-is.
> 2) Add Qt-style wrappers around std::* smart pointers and move old
> implementations of Qt smart pointers to the Qt5Compact module.
> Both options have pros and cons. It would be useful to hear your
> thoughts on it. It’s worth mentioning that some other options, like
> using Qt smart pointers as-is, were also discussed. They were found less
> suitable, but feel free to share your opinion if you disagree.
> Another thing to discuss is whether we should use raw pointers in the
> API at all or not. There are a few options again:
> 1) Yes
> 2) No. Use “modern” approaches instead (pass mandatory dependencies by
> either reference or const reference when using smart pointers makes no
> sense, use something optional-like or tuples to return extra data from
> functions, and so on)
> 3) Mix 1 and 2.
> There are pros and cons for all options. Share your opinion once again,
I really relaly like the direction of the change that Allan proposes, so
my opinion is (3). Introduce the use of std::unique_ptr overloads where
applicable in our API, keep QObject parent/child as is and go with this
and learn. The unique_ptr really _adds_ to our API here, makes it
There is API that uses QSharedPointer today, some QPA platform dialog
bits and for example QSharedPointer<QQuickItemGrabResult>
grabToImage(const QSize &targetSize = QSize());
I still believe that the less #ifdefs our users have to paste into their
code base when using Qt 5 and 6, the more people will transition and I
think that's critical to success. That is what makes me think we should
keep existing QSharedPointer API. There might be more in "leaf" modules.
More information about the Development