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

前端 未结 4 1881
清歌不尽
清歌不尽 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:32

    Here is another approach I've seen used, apparently known as the passkey idiom : have the public constructor require a private access token.

    class Spam {
        struct Token {};
        friend void Foo();
    public:
        Spam(Token, int mem) : mem(mem) {}
    
    private:
        int mem;
    };
    
    void Foo() {
        std::unique_ptr spam = std::make_unique(Spam::Token{}, 10);
    }
    
    void Bar() {
        // error: 'Spam::Token Spam::token' is private
        // std::unique_ptr spam = std::make_unique(Spam::Token{}, 10);
    }
    

提交回复
热议问题