How to store a reference of a singleton class?

后端 未结 1 1494
旧时难觅i
旧时难觅i 2020-12-04 00:26

I am working on a project relating to a dealer dealing cards to players.
I have the singleton class Dealer and another class called Player.

相关标签:
1条回答
  • 2020-12-04 00:44

    In the first place you should ask yourself, if you really need a singleton class to solve this problem at all.

    You can always pass the reference to an instance of Dealer to the constructor of your Player class:

    class Player {
    public:
        Player(Dealer& dealer_) : dealer(dealer_) {}
    
    private:
        Dealer& dealer;
    };
    

    no matter, wether it was constructed on the stack, on the heap or as singleton instance.


    For the singleton Player class, how do I create a private member ..._

    The commonly recommended c++ singleton implementation pattern is

    class Dealer{
    public:
         static Dealer& instance() {
             static Dealer theDealer;
             return theDealer;
         }
    
         void foo() {}
    private:
         Dealer() {}
         Dealer(const Dealer&) = delete;
         Dealer& operator=(const Dealer&) = delete;
    };
    

    NOTE: You don't necessarily need to store a reference to Dealer class in your client class, but you can simply access the singleton instance and call the desired non static member function

    Dealer::instance.foo();
    

    If you insist to create a reference member to the singleton though, you can do:

    class Player {
    public:
        Player() : dealer(Dealer::instance()) {}
    
    private:
        Dealer& dealer;
    };
    
    0 讨论(0)
提交回复
热议问题