[Development] unique_ptr and Qt, Take 2

Scott Bloom scott at towel42.com
Fri May 3 20:43:03 CEST 2019


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?

--
I just survived a painful problem dealing with this exact issue.

Long story short, a child widget, had to survive the parent, it was created correctly with parent being null, but in adding it to a layout, changed that of course.

The solution was to set the parent back to null, when the "non-layout" parent's destructor was called.

A Qt Smart Pointer, that allowed "unique" but another that also allowed for "Shared" depending on the case, that took into account the Qt parent child relationship, would be a great addition

Scott


More information about the Development mailing list