【发布时间】:2020-03-03 19:18:47
【问题描述】:
我有一个Context 类,我希望每个人都只能通过 unique_ptr 来管理它(通过提供的NewInstance 静态方法)。
所以我删除了该类的副本/ctor 并提供了一个 NewInstance 方法。
class Context
{
public:
Context(const Context&) = delete;
Context& operator=(const Context&) = delete;
static std::unique_ptr<Context> NewInstance()
{
return std::make_unique<Context>();
}
private:
Context()
{
}
};
但是,当我这样称呼它时
void func()
{
auto ctx = Context::NewInstance();
}
我得到一个编译错误,说
error: ‘Context()’ is private within this context
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
我猜是因为我将Context()设为私有(因为我不想让其他人直接构造它)。
我也尝试将static NewInstance 设为Context 的好友函数,但错误仍然存在。
那么,让一个类只能通过几种方法构造的模式是什么?
【问题讨论】:
-
重复解释问题,但由于这是
std::unique_ptr,您可以这样做:return std::unique_ptr<Context>{new Context};,而不会损害任何优化。
标签: c++ class private smart-pointers