0

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?

Yves
  • 11,597
  • 17
  • 83
  • 180

1 Answers1

1

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.

Caleth
  • 52,200
  • 2
  • 44
  • 75
  • `the specific sequence of numbers`: do you mean that `static mt19937` may produce the same sequence number for `t1.func()` and `t2.func()`? – Yves Feb 25 '22 at 10:02
  • @Yves no, `t1.func(); t1.func();` would be the same as `t1.func(); t2.func();` etc (assuming the seed was the same) – Caleth Feb 25 '22 at 10:04
  • Alright, I think I would make `mt19937` non static but make the two `std::uniform_int_distribution` static... – Yves Feb 25 '22 at 10:15