1

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?

Bin Yan
  • 117
  • 8
  • 3
    Duplicate explains issue, but since this is `std::unique_ptr` you can just do: `return std::unique_ptr{new Context};` without harming any optimization. – Marek R Mar 03 '20 at 10:54

1 Answers1

1

A simple way is to build a new object and create a std::unique_ptr from it:

static std::unique_ptr<Context> NewInstance()
{
    Context *ctx = new Context();
    return std::unique_ptr<Context>(ctx);
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252