Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507393

Is gsl::owner usable for shared-ownership?

For example, can it be used in Qt for the following?

gsl::owner<QWidget*> w{new QWidget{parent}}

In this example, the ownership is shared by the new-site and the parent, because the code who has new-ed the object can delete w, and W's destructor will take itself out of parent children list. However, if w is not deleted at the new-site, then parent will delete it in its destructor.

  1. Is this an example of shared ownership, and
  2. can gsl::owner be used for it?

Upvotes: 0

Views: 211

Answers (2)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29995

In this example, the ownership is shared by the new-site and the parent, because the code who has new-ed the object can delete w, and W's destructor will take itself out of parent children list. However, if w is not deleted at the new-site, then parent will delete it in its destructor.

This is wrong. The code that has created this object should not delete it unless it is absolutely sure that the parent is still alive, otherwise you will get double-free errors (because parent would have freed the object already).

The correct solution is to use QPointer as mentioned in the other answer.

Upvotes: 1

Caleth
Caleth

Reputation: 63227

Is this an example of shared ownership

No, you have two places claiming unique ownership.

can gsl::owner be used for it

If w can outlive the object pointed to by parent, then it might become invalid, leading to undefined behaviour.

If you want a pointer type that interfaces with Qt's parent-child ownership, use QPointer

Upvotes: 2

Related Questions