When should you use 'friend' in C++?

前端 未结 30 1663
孤街浪徒
孤街浪徒 2020-11-22 10:12

I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.

30条回答
  •  难免孤独
    2020-11-22 10:53

    Friends are also useful for callbacks. You could implement callbacks as static methods

    class MyFoo
    {
    private:
        static void callback(void * data, void * clientData);
        void localCallback();
        ...
    };
    

    where callback calls localCallback internally, and the clientData has your instance in it. In my opinion,

    or...

    class MyFoo
    {
        friend void callback(void * data, void * callData);
        void localCallback();
    }
    

    What this allows is for the friend to be a defined purely in the cpp as a c-style function, and not clutter up the class.

    Similarly, a pattern I've seen very often is to put all the really private members of a class into another class, which is declared in the header, defined in the cpp, and friended. This allows the coder to hide a lot of the complexity and internal working of the class from the user of the header.

    In the header:

    class MyFooPrivate;
    class MyFoo
    {
        friend class MyFooPrivate;
    public:
        MyFoo();
        // Public stuff
    private:
        MyFooPrivate _private;
        // Other private members as needed
    };
    

    In the cpp,

    class MyFooPrivate
    {
    public:
       MyFoo *owner;
       // Your complexity here
    };
    
    MyFoo::MyFoo()
    {
        this->_private->owner = this;
    }
    

    It becomes easier to hide things that the downstream needn't see this way.

提交回复
热议问题