Friday 15 February 2013

c++ Singleton by reference use -



c++ Singleton by reference use -

i have read of wikis in stackoverflow, , i've written next header file 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 next methods */ randomizer(randomizer const&); void operator= (randomizer const&); };

i have implemented of methods within of class, nextint , such.

i unsure how create instance of singleton class, i.e. how write test drive in main()?

i tried:

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

compiler says few errors:

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

thanks help.

you saying want singleton but:

randomizer r;

this constructs new instance of randomizer trying phone call default empty constructor. not using singleton, in add-on declared constructor private.

r = randomizer::instance();

here trying re-create assign singleton another, explicitly declared private.

maybe meant use:

randomizer &r = randomizer::instance()

probably it's improve have const randomizer& instance() method instead mutable reference if randomizer doesn't have visibile state.

c++ singleton

No comments:

Post a Comment