Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make_unique cannot access private constructor in static member

Tags:

c++

unique-ptr

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.

like image 780
Ward Segers Avatar asked Nov 28 '25 14:11

Ward Segers


1 Answers

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));
    }
};
like image 96
Ward Segers Avatar answered Nov 30 '25 03:11

Ward Segers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!