如何将对象的构造限制为几种方法?

How to limit the construction of an object to a couple of methods?

我有一个 Context class,我希望每个人都只能通过 unique_ptr(通过提供的 NewInstance 静态方法)来管理它。

所以我删除了 class 的 copy/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的友元函数,但是错误依然存在。

那么,仅通过几种方法即可构建 class 的模式是什么?

一种简单的方法是构建一个新对象并从中创建一个 std::unique_ptr:

static std::unique_ptr<Context> NewInstance()
{
    Context *ctx = new Context();
    return std::unique_ptr<Context>(ctx);
}