c++unique-ptr

make_unique cannot access private constructor in static member


My class has the following structure:

class S {
  public:
    S() {}
};

class T {
  private:
    S a;
    T(S s): a(s) {}

  public:
    static std::unique_ptr<T> make_item() {
        S s_instance;
        return std::make_unique<T>(s_instance);
    }
};

However, when I try to make a unique_ptr in the make_item, it sees the constructor as private.

Is there a way to allow the use of the private constructor in a static member function of the class itself? Because one member is a unique_ptr to S (a rather heavy object), we wish not to use a copy.


Solution

  • As proposed by yksisarvinen in the comments, a way to solve this is to just replace make_unique<T> by std::unique_ptr<T>(new T(S)).

    class S {
      public:
        S() {}
    };
    class T {
      private:
        S a;
        T(S s): a(s) {}
    
      public:
        static std::unique_ptr<T> make_item() {
            // Create S
            S s_instance;
            return std::unique_ptr<T>(new T(s_instance));
        }
    };