I’m trying to generate random numbers with boost, and I’m having trouble getting it to work in a way that keeps everything encapsulated. I’ve got this piece of code in main(), which allows me to use roll() to generate a random number from [0,1)
boost::mt19937 rng(seed);
boost::uniform_01<> uniform_p;
boost::variate_generator< boost::mt19937, boost::uniform_01<> >
roll(rng, uniform_p);
Now I want to stick this in its own header/cpp file, with one function to obtain a seed and create roll, and others that call roll. But nothing can seem to see roll, and I’m pretty sure it will go out of scope after the function that calls it goes out of scope. I’ve tried playing around with static and extern, I’ve tried making roll part of a class so it won’t go out of scope, but nothing seems to work.
The following is a Matlab-like interface which I like to use for the generation of random numbers. You have to call
seed()before usingrand(). As Greg pointed out,scoped_ptris handy to store the static variables (the Mersenne twister and the variate generator) which are needed. For thread-safety, protect these ressources with mutexes.random.hpp
random.cpp
main.cpp