DBear
DBear

Reputation: 491

C++11 "default" UniformRandomBitGenerator (URBG)

I have a C++ application that requires some basic randomness in various places throughout the codebase. What is the best practice for obtaining randomness with the C++11 PRNG library?

Specifically, I'm looking for something similar to Java's ThreadLocalRandom that will suffice as a URBG (UniformRandomBitGenerator) that I can use on-demand when I don't need anything fancy. I thought the default_random_engine looked promising, but this doesn't solve the whole issue because I don't want to deal with seeding one of these every time I need randomness.

My current solution is to write two source files -- two lines each -- to declare/define a shared URBG that I can use anywhere in my application:

// my_random.hpp
#include <random>
extern std::default_random_engine my_urbg;
// my_random.cpp
#include <random>
std::default_random_engine my_urbg(std::random_device()());

so I can use it like this:

// some_application_source.cpp
#include "my_random.hpp"
...
int my_number = std::uniform_int_distribution(0,99)(my_urbg);
...

But I can't be the only one who wants this, so I figured I'd ask if there's a better way that I'm just missing. Perhaps something in the C++ standard library that achieves this...? Perhaps something thread-safe...? Perhaps something more proper than two tiny files...?

Upvotes: 4

Views: 91

Answers (0)

Related Questions