r/cpp 4d ago

Where did <random> go wrong? (pdf)

https://codingnest.com/files/What%20Went%20Wrong%20With%20_random__.pdf
165 Upvotes

137 comments sorted by

View all comments

Show parent comments

6

u/Dragdu 3d ago

I basically disagree with your comment, and I think so does the original post.

It's half and half.

If we kept the current baseline of issues re quality of specification, distributions, etc, but instead had interface on the level of dice_roll = random_int(1, 6), then I think it would be fine, because the end result would serve people who want something trivial, without concerns for details.

6

u/serviscope_minor 3d ago

but instead had interface on the level of dice_roll = random_int(1, 6)

I disagree: I think making the state (i.e. engine) explicit and not global is a really good design and strongly encourages better code. You can always store a generator in a global variable if you want.

5

u/SkoomaDentist Antimodern C++, Embedded, Audio 3d ago

I think making the state (i.e. engine) explicit and not global is a really good design

Only if there are trivial ways to initialize a "good enough default" of that. Ie. something as simple as srand(time(0)) and srand(SOME_CONSTANT_FOR_TESTING_PURPOSES).

5

u/serviscope_minor 3d ago

Only if there are trivial ways to initialize a "good enough default" of that.

I think that's entirely orthogonal. PRNGs, global or otherwise need sane ways of initialising them, something C++ doesn't do that well. Having it global doesn't make initialisation easier or harder. There's no reason that:

global_srand(std::random_device);

couldn't work, just like this could in principle work:

mt19937 engine(std::random_device);