-2

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;
}
YSC
  • 38,212
  • 9
  • 96
  • 149
Carbon
  • 3,828
  • 3
  • 24
  • 51
  • I think you mean "assigning the result of a function to a `std::shared_ptr`". The direction of assignment is from the right side to the left side. – molbdnilo Sep 12 '17 at 13:33
  • Is `SpecialPotato()` meant to be a function creating a specialization (derived class) of `Potato`? – user0042 Sep 12 '17 at 13:51

2 Answers2

5

*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 */);
}   
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • OP asked for a _one liner_. Is that function really needed? – user0042 Sep 12 '17 at 13:34
  • @user0042 I have no idea. The OP was using a function with 3 lines so I gave them a function with one. It's up to them to decide if they even need a function. – NathanOliver Sep 12 '17 at 13:46
  • Seems OP want's to use `SpecialPotato` as prototype or another function that returns a shared pointer creating a _special sort of potato_. I can't fully decipher what they actually want. – user0042 Sep 12 '17 at 13:49
  • @user0042 Seems simple enough. They are using 3 lines right now and want to simplify it. If it is not what they want they will probably comment. – NathanOliver Sep 12 '17 at 13:50
  • Looks a bit like a XY problem for me. Voted to close as _unclear_. – user0042 Sep 12 '17 at 13:52
0

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.

YSC
  • 38,212
  • 9
  • 96
  • 149
  • What's the advantage about taking a copy? – user0042 Sep 12 '17 at 14:09
  • @user0042 not my design: `SpecialPotato()` returns by value. Without any optimization, building a `std::shared_ptr` from a value copies the value. Why the downvote? – YSC Sep 12 '17 at 14:50