假设我有一个没有公共(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
(orstd::make_unique
)?
没有这样的方法。 std::make_shared
和 std::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/