C++11 智能指针 Make 可变大小对象函数

标签 c++ c++11 smart-pointers factory-method

假设我有一个没有公共(public)构造函数但有静态工厂或构建器方法的类,创建的对象的大小取决于传递给工厂(或构建器)的参数。

有没有办法使用 std::make_shared(或 std::make_unique)创建指向此类对象的共享(或唯一)指针?

对于任何建议的多态性,我更喜欢模板而不是虚拟方法。

最佳答案

Consider I have a class with no public constructor ...

Is there a way to create a shared (or unique) pointer to such an object using std::make_shared (or std::make_unique)?

没有这样的方法。 std::make_sharedstd::make_unique 需要公共(public)构造函数。

相反,您可以创建共享(唯一)指针而无需方便的“make”函数:

// within the factory
return std::shared_ptr<T>(new T(size));

附言。 C++11 标准库没有std::make_unique

关于C++11 智能指针 Make 可变大小对象函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43966450/

相关文章:

c++ - WinApi 控件未显示在主窗口中

c++ - boost 范围适配器变平

c++ - C++ 中有一些更智能的智能指针吗?

C++11 智能指针用例

c++ - 为什么日历周数在星期一凌晨 3 点更新,而不是在午夜?

c++ - Qt:3D水平条形图

c++ - 在参数中移出的智能指针上调用方法是否安全?

c++ - std::vector 成员变量可以未初始化(内存错误)吗?

c++ - 为什么需要闭包类型的引用成员?

c++ - 保留超出范围的类的数据?