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?
5 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.
-
2shouldn't that be
std::make_shared<Foo>(FuncThatReturnsFoo(...))
?– josefxCommented Aug 16, 2012 at 17:22 -
1I think the template parameter to make_shared needs to be explicit.
make_shared<Foo>(FuncThatReturnsFoo(...))
.– bames53Commented Aug 16, 2012 at 17:33 -
@bames53: I was going to fix it, but Jonathan got there first. Commented Aug 16, 2012 at 17:45
I wouldn't do that if I were you. Mainly because std::shared_ptr
manages memory, whereas if you get an object as a return type, the memory is managed automatically (usually, and most likely).
You'll either have to 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 manage.
Foo getObject();
//becomes
Foo* getObject();
//or, even better
std::shared_ptr<Foo> getObject();
There are two ways to do this:
- Create a new copy on the heap and make a shared_ptr from that.
- Make a shared_ptr from it with a null deleter.
The first can be done by writing
auto newPtr = std::make_shared<Foo>( foo );
This works, if the class Foo
is copy-constructable. The second thing can be accomplished by
auto newPtr = std::shared_ptr<Foot>( &foo, [](void*){} );
Here you don't create a new copy of the object. However, this is only safe, if you can guarantee that the pointer is not accessed, after foo
goes out of scope. Otherwise, you will access a destroyed object and you program is likely to do random stuff.
I suspect you want to prevent heap-allocation otherwise just heap-allocate a copy of the returned object and go ahead.
You need to prevent that the deleter actually deletes something and need the 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);
That is a real code smell, though. Why would a function accept a
shared_ptr
if not to extend life-time?
You can do this
std::shared_ptr<Foo> ptr(new Foo(f());
Semantically, it's making a copy of the return value, but the copy constructor should be elided.
shared_ptr
arguments is suboptimal and should be avoided.