vendredi 25 février 2022

It is proper to make mt19937 static in a class

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?

Aucun commentaire:

Enregistrer un commentaire