Search code examples
c++shared-ptr

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


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?


Solution

  • 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.