यह एक 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
{ }
};
आप उपरोक्त make_foo
में Foo::make
लपेट सकते हैं, या इसे सीधे का उपयोग करें:
auto f = Foo::make(true, 'x', Blue);
कहा कि, जब तक आप वास्तव में साझा करना स्वामित्व, std::unique_ptr<Stuff>
अधिक बेहतर दृष्टिकोण की तरह लगता है: यह अवधारणात्मक रूप से बहुत सरल और कुछ और अधिक कुशल है। उस स्थिति में आप #1
चिह्नित लाइन में m_myStuff(new Stuff(std::forward<Args>(args)...))
कहेंगे।
स्रोत
2012-08-17 08:47:34
@sellibitze टाइपो – Baz
वास्तव में नहीं, 'Foo' * स्वामित्व नहीं लेता है। 'Shared_ptr' का बिंदु * साझा * स्वामित्व है। – juanchopanza
या 'std :: shared_ptr foosStuff (नया सामग्री());' –
stefaanv