Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move ownership from std::shared_ptr to std::unique_ptr

I have a class A which has a field of type std::unique_ptr:

class A
{
public:
   std::unique_ptr pointer;
// class body
};

And somewhere in code, I'm using few std::shared_ptrs which point to the same object. Now what I'd like to achieve is to move ownership to this std::unique_ptr in my class, so that if all shared_ptrs will be destroyed, my object will stay alive as long as this unique_ptr will stay alive.

My question is - is it possible to move ownership from std::shared_ptr to std::unique_ptr and if yes, how can I do this?

like image 932
Piotr Chojnacki Avatar asked Mar 11 '13 11:03

Piotr Chojnacki


People also ask

Can I convert shared_ptr to unique_ptr?

Afterword. The flawless conversion of an std::unique_ptr to a compatible std::shared_ptr makes it possible to write efficient and safe factory functions. However, note that an std::shared_ptr cannot be converted to an std::unique_ptr.

How do you transfer ownership in C++?

In C++11 we can transfer the ownership of an object to another unique_ptr using std::move() . After the ownership transfer, the smart pointer that ceded the ownership becomes null and get() returns nullptr.

Should I use shared_ptr or unique_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

Can you copy shared_ptr?

After you initialize a shared_ptr you can copy it, pass it by value in function arguments, and assign it to other shared_ptr instances.


1 Answers

Logically such a scenario doesn't make sense to me.

Suppose for a while that it is possible to transfer the ownership, but you could do that only when you're sure that there is only one shared_ptr alives; if that is the case, then you can still use shared_ptr as member of A and pretend that it is unique_ptr.

And then you commented:

That's true, I could create shared_ptr in A class. I think I misunderstood a concept a bit again. I wanted to behave it in this way: if unique_ptr dies, the object itself dies too, even though shared_ptrs still point to it, but that's silly as they wouldn't know that object itself was destroyed and therefore they wouldn't be nullptrs.

In that case, you're looking at the wrong smart pointer. What you probably need is called std::weak_ptr. If so, then make sure you use one std::shared_ptr and all others as std::weak_ptr.

like image 140
Nawaz Avatar answered Sep 28 '22 05:09

Nawaz