Initiation std:unique_ptr in friendly class



  • Hi.

    It's a simple problem, but I've never encountered it, and there's no easy way to find it, so I decided not to lose the power and time and ask a question.

    Example:

    #include <memory>
    

    struct A {
    protected:
    A() {}
    friend class B;
    };

    struct B {
    std::unique_ptr <A> a;
    B() : a( std::make_unique<A>() ) {}
    };

    int main() {
    B b;
    }

    This example is not compromised. But if you do. protected or replace std:unique_ptr I'll be fine.

    I don't want to get rid of either one.
    How?



  • Function std::make_unique is not a friendly function for class A♪ Therefore, it cannot create class objects A

    But you can write

    B() : a( new A() ) {}
    

    This is a simple demonstration program.

    #include <memory>
    

    int main()
    {
    struct A
    {
    protected:
    A() {}
    friend struct B;
    };

    struct B 
    {
        std::unique_ptr &lt;A&gt; a;
        B() : a( new A() ) {}
    };
    
    B b;
    

    }


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2