【问题标题】:How to limit the construction of an object to a couple of methods? [duplicate]如何将对象的构造限制为几种方法? [复制]
【发布时间】: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&lt;Context&gt;{new Context};,而不会损害任何优化。

标签: c++ class private smart-pointers


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    相关资源
    最近更新 更多