Friend function is unable to construct a unique pointer of the class

前端 未结 4 1869
清歌不尽
清歌不尽 2021-02-13 13:45

I have a certain design strategy where the constructor of my class is private and can only be constructed by friends of the class. Inside the friend function, I am trying to cre

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-13 14:34

    Why am I not able to compile?
    

    You are unable to compile because make_unique is not a friend of Spam.

    An alternative solution to making make_unique a friend is to move the creation of the unique_ptr into Spam.

    class Spam {
       ...
    private:
       Spam(int) {}
    
       static unique_ptr create( int i ) 
       { return std::unique_ptr( new Spam(i) ); }
    };
    

    and then have Foo call that instead.

    void Foo() {
        std::unique_ptr spam = Spam::create(10);
        ...
    }
    

提交回复
热议问题