There's gotta be a more idiomatic way to do this:
Potato SpecialPotato();
std::shared_ptr<Potato> givePotato()
{
std::shared_ptr<Potato> ret;
*ret = SpecialPotato();
return ret;
}
There's gotta be a more idiomatic way to do this:
Potato SpecialPotato();
std::shared_ptr<Potato> givePotato()
{
std::shared_ptr<Potato> ret;
*ret = SpecialPotato();
return ret;
}
*ret = SpecialPotato(); is not going to work as ret is just a null pointer as it was default constructed. If you want to return a std::shared_ptr<Potato> that points to a Potato with the value that SpecialPotato() returned then you can use std::make_shared like
std::shared_ptr<Potato> givePotato()
{
return std::make_shared<Potato>(SpecialPotato());
}
This will dynamically allocate a Potato, initialize it with the return of SpecialPotato() and then return the shared_ptr.
Do note that if SpecialPotato() is supposed to return a type that is derived from Potato then you can't return a Potato. That will slice the object and you you lose the derived part of the object. When returning a derived type as a parent type you need to use a pointer/pointer-like type like
std::shared_ptr<Potato> SpecialPotato()
{
return std::make_shared<SpecialPotatoType>(/* constructor parameters here */);
}
Use std::make_shared:
Potato SpecialPotato();
std::shared_ptr<Potato> givePotato()
{
return std::make_shared<Potato>(SpecialPotato());
}
It has the pro to build the std::shared_ptr and the object copy in one pass. Moreover, the copy may be optimized out.