Jon*_*ove 1 c++ constructor std shared-ptr
当我写作
std::shared_ptr<MyType> x;
Run Code Online (Sandbox Code Playgroud)
使用指向nullptr的空共享指针初始化x.但我希望它能自动调用MyType的默认(或其他一些指定的构造函数).我知道,我可以写:
std::shared_ptr<MyType> x = std::maked_shared<MyTYpe>();
Run Code Online (Sandbox Code Playgroud)
但有时人们会忘记然后你遇到麻烦,所以编译器强制执行此操作会很好.
您可以创建一个类,例如:
template <typename T>
struct defaulted_shared_ptr : std::shared_ptr<T>
{
    using std::shared_ptr<T>::shared_ptr;
    defaulted_shared_ptr() : std::shared_ptr<T>(std::make_shared<T>()) {}
};
Run Code Online (Sandbox Code Playgroud)
然后
defaulted_shared_ptr<Foo> foo;
Run Code Online (Sandbox Code Playgroud)
将包含默认构造 Foo