8

I'm trying with no luck to use the std::mt19937 generator as a class member but I always get the same result. This is an example of what I'm trying.

class Level { public: Level(); private: int generateTokenType(); std::mt19937 m_mt; std::random_device m_randomdevice; }; Level::Level(): m_mt(m_randomdevice()) { } int Level::generateTokenType() { std::uniform_int_distribution<int> dist(0, 10); return dist(m_mt); } 

What I want, is to maintain the generator created and ask for numbers during program execution.

-- Edit -- Following Cornstalks answer I did that:

class Level { public: Level(); private: int generateTokenType(); std::mt19937 m_mt; }; Level::Level(): m_mt((std::random_device())()) { for(auto i = 0; i < 10; i++) std::cout<<generateTokenType()<<" "; std::cout<<std::endl; } int Level::generateTokenType() { std::uniform_int_distribution<int> dist(0, 10); return dist(m_mt); } 

But on every execution I get the same numbers...

2
  • 3
    First, no need to be harsh. And second, I'm not getting a compiler warning. Commented Apr 11, 2015 at 17:39
  • 2
    As an advice, try enabling all warnings. For gcc or clang use -Wall. If you use an IDE, select an appropriate option in the project/environment setting. This should help you in the future. Commented Apr 11, 2015 at 17:46

1 Answer 1

11

Move std::random_device m_randomdevice; before std::mt19937 m_mt;.

In C++, members are constructed/initialized in the order that they're declared in the class. Your constructor is calling m_randomdevice() before m_randomdevice has even been constructed.

Alternatively, get rid of the m_randomdevice member. You could just do m_mt((std::random_device())()) to initialize m_mt.

Sign up to request clarification or add additional context in comments.

6 Comments

Something is crazy, I did what you said but I get always the same numbers. I checked the code here link and it works ok, but .. maybe it's something related to MinGW?
@FrameBuffer: mingw has had a broken std::random_device. Perhaps it is still broken. stackoverflow.com/questions/18880654/…
Yes definitely it's broken in the version I'm using .. well, I will try to workaround that.. thank you. I will mark this answer as correct, because this mingw thing is not related to my question.
@Bill Shouldn't std::uniform_int_distribution<> also be a class member for it to work correctly? A fresh distribution object is created on every call of Level::generateTokenType() as per the question.
@legends2k: Looking at the libc++ implementation, it looks pretty cheap to instantiate. github.com/llvm/llvm-project/blob/main/libcxx/include/__random/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.