1

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.

luator
  • 4,769
  • 3
  • 30
  • 51
  • 5
    What is the full signature of `create_foo`? Does Foo have a copy and/or move constructor? – Botje Aug 27 '20 at 11:52
  • 1
    A [mcve] would help. – Eljay Aug 27 '20 at 12:08
  • 1
    One idea might be to return a `std::unique_ptr` from your factory. This does not enforce additional ownership rules over returning the object directly. Also a `std::unique_ptr` is directly consumable by a `std::shared_ptr`. (https://gcc.godbolt.org/z/1M4b9v) – Simon Kraemer Aug 27 '20 at 12:18

1 Answers1

2

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());
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • This compiles without error, so I consider it a correct answer. I cannot fully verify as I get some issues at runtime but I think they are related to internals of `Foo` not being moved properly which is beyond the scope of this question. – luator Aug 28 '20 at 07:27