【发布时间】:2019-06-24 19:58:55
【问题描述】:
考虑下面的代码,我想将 A 对象的创建委托给一个名为 make 的方法,以允许该类的用户只创建包装在 std::shared_ptr 中的实例:
#include <memory>
class A {
private:
A() {}
public:
static std::shared_ptr<A> make() {
return std::make_shared<A>();
}
};
int main() {
std::shared_ptr<A> a = A::make();
return 0;
}
我本来以为,因为make 是一个成员函数,它会被允许访问私有构造函数,但显然情况并非如此。编译程序失败,std::shared_ptr 的源代码中出现以下消息:
/usr/include/c++/8/ext/new_allocator.h:136:4: error: ‘A::A()’ is private within this context
我该如何解决这个问题?
【问题讨论】:
-
您可以考虑使用pass key idiom。
-
这与静态函数无关。就是
std::make_shared试图构造一个A,因为构造函数是私有的,所以它不能。
标签: c++ class shared-ptr