hlx98007
hlx98007

Reputation: 241

c++ Singleton by reference use

I have read some of the wikis in StackOverflow, and I've written the following header file for my Randomizer class:

class Randomizer
{
    public:
        static Randomizer& instance(void);
        int nextInt(int);
        int nextInt(int, int);
        int die(int);
        double nextDouble(void);
        char randomChar(const std::string&);
    private:
        Randomizer(void) {};
        /* No implementation of the following methods */
        Randomizer(Randomizer const&);
        void operator= (Randomizer const&);
};

I have also implemented some of the methods inside of the class, like nextInt and such.

I am unsure about how to make an instance of this Singleton class, i.e. how to write a test drive in main()?

I tried:

int main()
{
     Randomizer r;
     r = Randomizer::instance();
}

Compiler says a few errors:

In file included from Randomizer.cpp:11:0:
Randomizer.h: In function ‘int main(int, char**)’:
Randomizer.h:22:9: error: ‘Randomizer::Randomizer()’ is private
         Randomizer(void) {};
         ^
Randomizer.cpp:56:16: error: within this context
     Randomizer r;
                ^
In file included from Randomizer.cpp:11:0:
Randomizer.h:25:14: error: ‘void Randomizer::operator=(const Randomizer&)’ is private
         void operator= (Randomizer const&);
              ^
Randomizer.cpp:57:7: error: within this context
     r = Randomizer::instance();
       ^

Thanks for help.

Upvotes: 2

Views: 1349

Answers (2)

Denys Bulant
Denys Bulant

Reputation: 315

This code tries to copy the Randomizer instance. If you don't want to directly use the result of the instance() call, you should take the returned reference:

Randomizer &r = Randomizer::instance();

Upvotes: 5

Jack
Jack

Reputation: 133669

You are saying that you want a singleton but:

Randomizer r; 

This constructs a new instance of Randomizer by trying to call the default empty constructor. So you are not using it as a singleton, in addition you declared the constructor private.

r = Randomizer::instance();

Here you are trying to copy assign a singleton to another, which you explicitly declared private.

Maybe you meant to use:

Randomizer &r = Randomizer::instance()

Probably it's also better to have a const Randomizer& instance() method instead that a mutable reference if the randomizer itself doesn't have a visibile state.

Upvotes: 5

Related Questions