Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a std::shared_ptr from a non-pointer object?

Tags:

c++

shared-ptr

As output from one function, I get an object of type Foo. As an argument to another class, I need to pass an object of type std::shared_ptr<Foo>. How can I make the shared pointer from the original object?

like image 773
Jim Avatar asked Aug 16 '12 17:08

Jim


People also ask

How can a Weak_ptr be turned into a shared_ptr?

The weak_ptr class template stores a "weak reference" to an object that's already managed by 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.

Why would you choose shared_ptr instead of 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.

Should we pass a shared_ptr by reference or by value?

Pass the shared_ptr by value. This invokes the copy constructor, increments the reference count, and makes the callee an owner. There's a small amount of overhead in this operation, which may be significant depending on how many shared_ptr objects you're passing.

Can shared_ptr be copied?

The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr . Constructing a new shared_ptr using the raw underlying pointer owned by another shared_ptr leads to undefined behavior.


1 Answers

This is really quite simple:

auto val = std::make_shared<Foo>(FuncThatReturnsFoo(...));

Basically, just heap allocate a new Foo, copying/moving the result into it.

like image 183
Nicol Bolas Avatar answered Sep 28 '22 02:09

Nicol Bolas