code_fodder
code_fodder

Reputation: 16321

what happens if I reset a unique_ptr with a shared_ptr pointing to it?

I would be surprised if this is not answered somewhere already. But I have not found it.

Anyway, as the question says I want to know what happens if I create a shared pointer from a unique pointer. I saw some suggestions from here:

// Factor that returns unique_ptr
std::unique_ptr<ModelObject_Impl> factory();

// Store a shared_ptr to that returned unique_ptr
auto shared = std::shared_ptr<ModelObject_Impl>(factory());

Which got me thinking if I did something similar - where I have an owning-object that has a function that returns some internal object by unique_ptr - and I make a shared_ptr out of it (perhaps as suggested in the link). Then later if that owning-object destroys / resets its internal object - then what happens to my shared_ptr to it?

I know this is not quite what the link is suggesting to do - but I am not quite sure if this is a "good practise" or "undefined behaviour" - as far as I can tell, this would result in a dangling shared_ptr...

Upvotes: 1

Views: 611

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473272

where I have an owning-object that has a function that returns some internal object by unique_ptr - and I make a shared_ptr out of it (perhaps as suggested in the link). Then later if that owning-object

Stop. You have contradicted yourself. If object X owns object Y, and it returns a unique_ptr to Y, it no longer owns Y. That is what it means to return a unique_ptr to something.

If it returned a reference to a unique_ptr, well it doesn't matter because you either moved from it into your shared_ptr (in which case again, X no longer owns it), or you didn't, in which case you don't own it. Either way, ownership is unique.

To create a shared_ptr from a unique_ptr means that the shared_ptr claims ownership over the object. The unique_ptr no longer has it afterwards. That's why it takes an rvalue-reference to a unique_ptr; you have to move into the shared_ptr.

Upvotes: 4

Related Questions