Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

c++ - How to store a reference of a singleton class?

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.

I have made the instance() method for Dealer and this part is where I am confused:

For the singleton Player class, how do I create a private member called dealer that holds a reference to the singleton Dealer instance?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...