Search code examples
c++factorysmart-pointers

Create std::shared_ptr using factory function


I have a class Foo which is not instantiated directly but through a static factory method Foo Foo::create_foo().

Now I want to create a std::shared_ptr<Foo>. Normally I would use

auto ptr = std::make_shared<Foo>();

How can I achieve the same while using the factory?

I know that I could rewrite create_foo() to directly return a pointer but I'm wondering if there is a solution without changing the method.


Solution

  • If the Foo class have copy- or rvalue-constructor overloads (implicit or explicit) then you could use it as:

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