这可能是更有效的有make_foo
帮手:
Foo make_foo() { return Foo(std::make_shared<Stuff>()); }
现在你可以说auto f = make_foo();
。或者至少自己使用make_shared
调用,因为生成的shared_ptr
可能比由new
表达式构造的效率更高。
auto f = Foo::make(true, 'x', Blue);
这就是说,除非你:如果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
,或直接使用它真的是分享所有权,std::unique_ptr<Stuff>
听起来像更可取的方法:它在概念上更简单,也更有效。在这种情况下,您会在标记为#1
的行中说m_myStuff(new Stuff(std::forward<Args>(args)...))
。
@sellibitze typo – Baz 2012-08-17 08:41:49
不是真的,'Foo'不*取*拥有权。 'shared_ptr'的要点是*共享*所有权。 – juanchopanza 2012-08-17 08:43:44
或者更喜欢'std :: shared_ptr foosStuff(new Stuff());' –
stefaanv
2012-08-17 08:47:37