Initialization of static elements of an object

Static members sometimes confuse me. I understand how to initialize a simple built-in type, for example int , with something next to int myClass::statVar = 10; which you put in the .cpp file, but I have something like the following:

 class myClass { public: // Some methods... protected: static RandomGenerator itsGenerator; } 

The basic idea is quite simple: myClass needs access to a random generator for one of its member functions. I can also have only a few instances of the generator, since each object is quite large. However, the type of RandomGenerator must be “initialized”, so to speak, by calling RandomGenerator::Randomize() , which the compiler will not allow you to do, since it is not a constant value (is this correct?).

So how can I do this job?

Or maybe I should not use a static variable in this case and do it differently?

+1
source share
7 answers

You can create a wrapper class that will contain an instance of RandomGenerator in it and call RandomGenerator::Randomize in your constructor.

+2
source

Put it in a personal field, set a static accessor. In an accessory, if an element has not yet been initialized, initialize it.

+2
source

In such cases, singles are actually your friends, despite their other flaws.

+1
source

If RandomGenerator is RandomGenerator , you can use a helper function to initialize:

 RandomGenerator init_rg() { RandomGenerator rg; rg.Randomize(); return rg; } RandomGenerator myClass::itsGenerator = init_rg(); 
+1
source

Just write a function that returns a link to a correctly randomized RandomGenerator and turns its generator into a link to a generator:

 class myClass { public: // Some methods... protected: // make this a reference to the real generator static RandomGenerator& itsGenerator; public: static RandomGenerator& make_a_generator() { RandomGenerator *g=0; g=new RandomGenerator(); g->Randomize(); return *g; } } RandomGenerator& myClass::itsGenerator=myClass::make_a_generator(); 
+1
source

Is this just one function that needs RandomGenerator? You can do it as follows:

int myClass :: foo () {static RandomGenerator itsGenerator = RandomGenerator :: Randomize () ...}

0
source

If only myClass requires a RandomGenerator , then:

 myClass::myClass() { itsGenerator.Randomize(); } 

Does it matter if you re-randomize your random generator for each object? I do not accept, -)

0
source

Source: https://habr.com/ru/post/1496782/


All Articles