[Development] unique_ptr and Qt, Take 2

Giuseppe D'Angelo giuseppe.dangelo at kdab.com
Fri May 3 21:04:40 CEST 2019


Hi,

Il 03/05/19 19:22, Daniel Teske ha scritto:
> The first half of the program would thus look like:
> 
> QWidget widget;
> QHBoxLayout *layout = widget.makeChild<QHBoxLayout>();
> 
> QPushButton *leftButton = widget.makeChild<QPushButton>("LEFT");
> layout->addWidget(leftButton);
> 
> std::unique_ptr<QPushButton> rightButton = 
> std::make_unique<QPushButton>("RIGHT");
> layout->addWidget(std::move(rightButton));

To really, really, really nitpick, this last line is (or feels) wrong: 
layouts do not take ownership of the widgets they manage. An ownership 
transfer MAY happen immediately (if the layout is installed) or later 
(as soon as the layout is installed).

> 
> For second half, the naive transformation:
> 
> {
>      QMenu menu;
>      auto act = std::make_unique<QAction>("Action!");
>      menu.addAction(act.get());
> menu.exec(leftButton->mapToGlobal(leftButton->rect().bottomLeft()));
> }
> 
> does no longer leak memory, instead the action is freed at the end of 
> the scope as its still owned by the unique_ptr.

Well, the super-naive transformation is actually already available:

> menu.addAction("Action!");

which correctly returns an action parented to the menu.


Anyhow, I too feel that we may need a dedicated smart pointer class for 
this, to catch all the corner cases and allow the existing flow of

1) create something
2) (re)parent it
3) keep using that something via a non-owning pointer.

My 2 c,
-- 
Giuseppe D'Angelo | giuseppe.dangelo at kdab.com | Senior Software Engineer
KDAB (France) S.A.S., a KDAB Group company
Tel. France +33 (0)4 90 84 08 53, http://www.kdab.com
KDAB - The Qt, C++ and OpenGL Experts

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 4329 bytes
Desc: Firma crittografica S/MIME
URL: <http://lists.qt-project.org/pipermail/development/attachments/20190503/a7527dab/attachment.bin>


More information about the Development mailing list