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

前端 未结 30 2013
孤街浪徒
孤街浪徒 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:37

    One specific instance where I use friend is when creating Singleton classes. The friend keyword lets me create an accessor function, which is more concise than always having a "GetInstance()" method on the class.

    /////////////////////////
    // Header file
    class MySingleton
    {
    private:
        // Private c-tor for Singleton pattern
        MySingleton() {}
    
        friend MySingleton& GetMySingleton();
    }
    
    // Accessor function - less verbose than having a "GetInstance()"
    //   static function on the class
    MySingleton& GetMySingleton();
    
    
    /////////////////////////
    // Implementation file
    MySingleton& GetMySingleton()
    {
        static MySingleton theInstance;
        return theInstance;
    }
    

提交回复
热议问题