C++ 如何将对象的构造限制为两种方法?
我有一个C++ 如何将对象的构造限制为两种方法?,c++,class,private,smart-pointers,C++,Class,Private,Smart Pointers,我有一个Context类,我希望每个人只通过unique_ptr(通过提供的NewInstance静态方法)来管理它 因此,我删除了类的copy/ctor,并提供了一个NewInstance方法 类上下文 { 公众: 上下文(const Context&)=删除; 上下文和运算符=(const Context&)=删除; 静态std::unique_ptr NewInstance() { 返回std::make_unique(); } 私人: 上下文() { } }; 然而,当我把它叫做 vo
Context
类,我希望每个人只通过unique_ptr(通过提供的NewInstance
静态方法)来管理它
因此,我删除了类的copy/ctor,并提供了一个NewInstance
方法
类上下文
{
公众:
上下文(const Context&)=删除;
上下文和运算符=(const Context&)=删除;
静态std::unique_ptr NewInstance()
{
返回std::make_unique();
}
私人:
上下文()
{
}
};
然而,当我把它叫做
void func()
{
auto ctx=Context::NewInstance();
}
我得到一个编译错误,说
error: ‘Context()’ is private within this context
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
错误:“Context()”在此上下文中是私有的
{::新建((void*)uu p)u向上(std::转发(u参数));}
我猜这是因为我将Context()
设为私有(因为我不希望其他人直接构造它)
我还尝试将静态NewInstance
作为上下文的友元函数,但错误仍然存在
那么,让一个类只能通过几个方法构造的模式是什么呢?一个简单的方法是构建一个新对象,并从中创建一个std::unique\u ptr
:
static std::unique_ptr<Context> NewInstance()
{
Context *ctx = new Context();
return std::unique_ptr<Context>(ctx);
}
static std::unique_ptr NewInstance()
{
Context*ctx=newcontext();
返回std::unique_ptr(ctx);
}
Duplicate解释了这个问题,但由于这是std::unique\u ptr
您只需执行以下操作:返回std::unique\u ptr{new Context}代码>不影响任何优化。