[Development] unique_ptr and Qt, Take 2

Niels Ole Salscheider niels_ole at salscheider-online.de
Fri May 3 20:42:23 CEST 2019


On 03.05.19 11:24, Thiago Macieira wrote:
> 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 agree that the ownership transfer of the unique_ptr feels a bit 
cumbersome and I also don't like that makeChild still returns raw 
pointers. Maybe something that understands the parent-child relationship 
can work better but I wonder how exactly it would look like.

Maybe using a combination of weak_ptr and shared_ptr would make the API 
easier to use?


More information about the Development mailing list