Podría ser más eficiente tener un ayudante make_foo
:
Foo make_foo() { return Foo(std::make_shared<Stuff>()); }
Ahora usted puede decir auto f = make_foo();
. O al menos use la invocación make_shared
usted mismo, ya que el resultante shared_ptr
puede ser más eficiente que el construido a partir de una expresión new
. Y si Stuff
realmente tiene argumentos de constructor, un constructor auxiliar privado podría ser adecuado:
struct Foo
{
template <typename ...Args>
static Foo make(Args &&... args)
{
return Foo(direct_construct(), std::forward<Args>(args)...);
};
private:
struct direct_construct{};
template <typeaname ...Args>
Foo(direct_construct, Args &&... args)
: m_myStuff(std::make_shared<Stuff>(std::forward<Args>(args)...)) // #1
{ }
};
Usted puede envolver Foo::make
en el anterior make_foo
, o usarlo directamente:
auto f = Foo::make(true, 'x', Blue);
Dicho esto, a menos que Realmente es compartir propiedad, un std::unique_ptr<Stuff>
suena como un enfoque más preferible: es conceptualmente mucho más simple y también algo más eficiente. En ese caso, diría m_myStuff(new Stuff(std::forward<Args>(args)...))
en la línea marcada #1
.
@sellibitze typo – Baz
En realidad, 'Foo' no * se apropia *. El objetivo de 'shared_ptr' es * compartir * propiedad. – juanchopanza
O prefiera 'std :: shared_ptr foosStuff (new Stuff());' –
stefaanv