Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an object instance to shared_ptr instance

Tags:

People also ask

How can a weak_ptr be turned into a shared_ptr?

To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock.

Can I assign a unique_ptr to shared_ptr?

The std::unique_ptr and std::shared_ptr are smart-pointers. An std::unique_ptr owns an object exclusively, whereas the ownership of an object can be shared via std::shared_ptr instances. One of the helpful features of unique_ptr is that it can be seamlessly converted to a compatible shared_ptr.

Why would you choose shared_ptr instead of unique_ptr?

In short: Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.

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.


Suppose I had two shared_ptr types such as

boost::shared_ptr<ObjA> sptrA;
boost::shared_ptr<ObjB> sptrB;

Now suppose that sptrA->SomeMethod() returned a simple ObjB type (not a shared ptr). Is it possible for me to store that type somehow in sptrB ? So that I could do something like this so that the returned type instance is automatically converted to boost_shared ptr

sptrB = sptrA->SomeMethod(); 

I asked this question just of curiosity and whether it is possible or not ?