11

According to the standard, std::random_device works the following way:

result_type operator()();

Returns: A non-deterministic random value, uniformly distributed between min() and max(), inclusive. It is implementation-defined how these values are generated.

And there are a couple of ways you can use it. To seed an engine:

std::mt19937 eng(std::random_device{}());

As an engine in itself:

std::uniform_int_distribution<> uid(1, 10);
std::cout << dist(dev);

Because it is implementation-defined, it doesn't sound as strong as say std::seed_seq or srand(time(nullptr)). Do I prefer to use it as a seed, as an engine or not at all?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
user4363909
  • 111
  • 1
  • 4
  • 1
    Unfortunately, you do have to be careful. For example, [MinGW doesn't implement `std::random_device` well](http://stackoverflow.com/q/18880654/10077). – Fred Larson Dec 15 '14 at 20:47
  • I would go for the first option, but it also depends on the quality of the engine you want to seed it with. – didierc Dec 15 '14 at 20:48
  • It could well be stronger than those techniques which are not cryptographically strong. Visual C++ for example uses [RtlGenRandom](http://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx). – Chuck Walbourn Dec 15 '14 at 20:48
  • I doubt you'll get a meaningful answer without specifying a compiler/platform on this one -- otherwise the best answer is to check your compiler's documentation for specifics. – MrEricSir Dec 15 '14 at 20:51
  • 3
    The source that `random_device` uses to fetch the random bits is implementation defined. So, if your implementation uses `/dev/random` instead of `/dev/urandom`, the call might block until you replenish the entropy pool, which might mean you'll spend a lot of time wiggling your mouse :) – Praetorian Dec 15 '14 at 20:52

1 Answers1

14

Generally speaking, std::random_device should be the source of the most truly random information you can access on your platform. That being said, accessing it is much slower than std::mt19937 or what not.

The correct behavior is to use std::random_device to seed something like std::mt19937.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • 1
    If I'm not mistaken, `std::random_device` could run out of entropy if you try to get a lot of numbers from it. That could cause it to block until you move the mouse or something. – Fred Larson Dec 15 '14 at 20:50
  • 1
    *Should* be, but sometimes isn't. See http://stackoverflow.com/questions/18880654/why-do-i-get-same-sequence-for-everyrun-with-stdrandom-device-with-mingw-gcc4 – Mark Ransom Dec 15 '14 at 20:56