[Development] unique_ptr and Qt, Take 2

Иван Комиссаров abbapoh at gmail.com
Fri May 3 20:41:16 CEST 2019

Thiago, can you please elaborate how you see this?

For a simple TreeItem a pair of std::unique_ptr/std::observer_ptr should be enough (with a bunch of convenience methods to insert children):

struct TreeItem
   observer_ptr<TreeItem> parent;
   vector<unique_ptr<TreeItem>> children;

Yes, the code becomes a bit verbose, but the ownership transfer is now visible with those (ugly) std::moves.

I can think of an alternative of using shared pointers (since we already have a QPointer aka WeakPointer<QObject>) but I think it gives too much overhead just to support corner cases.

If QLayout::addWidget() will return an observer_ptr*, you can just do

auto button = layout->addWidget(make_unique<QPushButton>(«RIGHT»));

* ok, you need a template version of addWidget for that, but since c++ is all about templates these days it doesn’t really a disadvantage

> 3 мая 2019 г., в 20:24, Thiago Macieira <thiago.macieira at intel.com> написал(а):
> On Friday, 3 May 2019 10:22:20 PDT Daniel Teske wrote:
>> std::unique_ptr<QPushButton> rightButton =
>> std::make_unique<QPushButton>("RIGHT");
>> layout->addWidget(std::move(rightButton));
> The problem in this particular example is that once you've added the widget, 
> the rightButton smart pointer no longer has a pointer. You can't continue to 
> set up your push button. In most cases, this is just a matter of moving the 
> set up before the addition / reparenting, or using the other idiom where the 
> object is never in a smart pointer in the first place.
> So this begs the question of whether std::unique_ptr is the best smart pointer 
> for this scenario. Would it make sense to create one that understands parent-
> child relationship?
> -- 
> Thiago Macieira - thiago.macieira (AT) intel.com
>  Software Architect - Intel System Software Products
> _______________________________________________
> Development mailing list
> Development at qt-project.org
> https://lists.qt-project.org/listinfo/development

More information about the Development mailing list