I have a Context
class, and I would like everyone to manage it ONLY through unique_ptr(by the provided NewInstance
static method).
So I delete the copy/ctor for the class and provide a NewInstance
method.
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()
{
}
};
However, when I call it like
void func()
{
auto ctx = Context::NewInstance();
}
I get a compile error, saying that
error: ‘Context()’ is private within this context
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
I guess it's because I made Context()
private(since I do not want other to construct it directly).
I also tried to make the static NewInstance
a friend function to Context
, but the error still exists.
So, what's the pattern to make a class constructable only through a couple of methods?