[Interest] Qt ownership model
Nye
kshegunov at gmail.com
Sat Jun 4 15:14:50 CEST 2016
Hello,
Since this is opinion based I will give my opinion without explicitly
stating it's just a personal view on the subject on every line.
On Sat, Jun 4, 2016 at 3:55 PM, Антон Жилин <antonyzhilin at gmail.com> wrote:
> A trend in modern C++ is AAA idiom.
>
The newest and hottest fad, which I consider to be a complete and utter
*rap.
The idea here is to *prohibit* new in user code, because ownership
> semantics of raw pointer is undefined.
>
That's a matter of some debate. I consider the ownership to be passed to
the person invoking new, unless otherwise stated (e.g. in Qt's
documentation the ownership transfer(s) are duly noted).
> How can we apply these idioms to Qt?
>
The question rather is: Should we?
> Yes, if we add a couple of helper functions!
>
> 1. Non-widgets can usually be constructed on stack or using
> std::unique_ptr -- Great
>
Applies to widgets as well. A stack allocation is much faster and robust
than new-ing needlessly. So if you don't need to keep binary compatibility
(e.g. when you have widgets in an application, or not directly exposed from
a library) I'd always opt for stack allocation. No need to have two heap
allocations, when I can get only one (the d-ptr of the QObject).
2. If we construct an object with a parent, we do something like this:
>
auto pushButton = new QPushButton(..., parent);
> -- Not so great, we need to look at parent to know if we need to delete
> pushButton
>
There was recently a thread on this same mailing list dealing with similar
issues. For most intents and purposes you can delete the child directly, if
that's not possible the deletion can be scheduled through the event loop. I
for one don't see any reason to complicate matters.
> 3. Widgets without a parent are usually used with QSharedPointer
>
"Usually"? Not in my experience. Widgets without a parent I just create in
the stack if possible. If not, I either use QScopedPointer when I own them,
or QPointer when ownership is transferred to Qt. I don't intend to share my
widgets, much less pass them across threads, so I don't see any good reason
why I would want to use a _shared_ pointer to keep reference to them
> What do you think?
>
Well that's pretty much what I think. You can agree or disagree, but I
really don't see any reason to embark in writing AAA-style.
Kind regards,
Konstantin.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20160604/26aca902/attachment.html>
More information about the Interest
mailing list