make_foo
有一个助手可能更有效:
Foo make_foo() { return Foo(std::make_shared<Stuff>()); }
现在你可以说auto f = make_foo();
。或者至少make_shared
自己使用调用,因为结果shared_ptr
可能比从new
表达式构造的更有效。如果Stuff
实际上采用构造函数参数,私有辅助构造函数可能是合适的:
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
{ }
};
您可以包装Foo::make
到上述make_foo
内容中,也可以直接使用它:
auto f = Foo::make(true, 'x', Blue);
也就是说,除非您真的共享所有权,否则std::unique_ptr<Stuff>
听起来更可取的方法是:它在概念上更简单,也更有效。在这种情况下,您会m_myStuff(new Stuff(std::forward<Args>(args)...))
在标记的行中说#1
。