How to make std :: shared_ptr from an object without a pointer?

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

+4
source share
5 answers

It is really quite simple:

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

Basically, just a bunch of it allocates a new Foo , copying / moving the result into it.

+7
source

I would not do this if I were you. Mostly because std::shared_ptr manages memory, whereas if you get an object as a return type, memory management happens automatically (usually and most likely).

You will have to either create a new object in dynamic storage

 Foo getObject(); //... std::shared_ptr<Foo> ptr(new Foo(getObject())); //construct new object in dynamic memory //using the copy constructor 

or change the function to return a pointer to an object whose memory you are managing.

 Foo getObject(); //becomes Foo* getObject(); //or, even better std::shared_ptr<Foo> getObject(); 
+5
source

I suspect that you want to prevent heap allocation, otherwise just a heap - select a copy of the returned object and continue.

You need to prevent the delector from actually deleting something and need a stack to take care of this:

 // given the signatures Foo f(); void other(std::shared_ptr<Foo> x); Foo my_f = f(); std::shared_ptr<Foo> my_fptr{&my_f, [](Foo*) {}}; other(my_fptr); 

This is the real smell of code. Why should a function accept shared_ptr if it does not extend the service life?

+1
source

There are two ways to do this:

  • Create a new copy on the heap and make shared_ptr out of it.
  • Make it shared_ptr with zero delete.

The first can be done by writing

 auto newPtr = std::make_shared<Foo>( foo ); 

This works if the Foo class is Foo . Second can be done

 auto newPtr = std::shared_ptr<Foot>( &foo, [](void*){} ); 

You are not creating a new copy of the object here. However, it is safe if you can guarantee that the pointer is not accessible after Foo goes out of scope. Otherwise, you will gain access to the destroyed object, and the program will most likely do random material.

+1
source

You can do it

 std::shared_ptr<Foo> ptr(new Foo(f()); 

Semantically, it makes a copy of the return value, but the copy constructor must be removed.

0
source

All Articles