Home > Mobile >  It is proper to make mt19937 static in a class
It is proper to make mt19937 static in a class

Time:02-26

Let's say I have a class as below:

class Test {
public:
    Test() : mt((std::random_device())()), dist1(0, 10), dist2(0, 100) {}
    void func() {
        if (dist1(mt) < 4) {
            // do something
        }
    }
    void func2() {
        if (dist2(mt) > 25) {
            // do something
        }
    }
private:
    std::mt19937 mt;
    std::uniform_int_distribution<int> dist1;
    std::uniform_int_distribution<int> dist2;
};

As you see, there are two functions, they all need a random number to do something.

In this case, can I make the data member std::mt19937 mt as static and initialize it in cpp file?

class Test {
...
private:
    static std::mt19937 mt;
...
};
// cpp file
std::mt19937 Test::mt((std::random_device())());

I just tried and it seemed to work. But I don't know if there is something wrong with it.

Test t1; t1.func(); t1.func2();
Test t2; t2.func(); t2.func2();

Can I say that static or non-static won't cause any difference for the piece of code?

CodePudding user response:

Can I say that static or non-static won't cause any difference for the piece of code?

If you care about the specific sequence of numbers that each instance of Test will observe, yes. However you are seeding these with std::random_device, so I suspect you don't care about that.

If you have calls to these methods on multiple threads, the static version has a data race. I would use thread_local, not static, to share std::mt19937s.

  • Related