dimanche 20 mars 2016

Static random number generator not seeded in different compilations units

I wanted to make an easy way to grab a random number, but unless I call Random::seed() in each cpp file, instead of just once at program start, the values generated in that cpp file will always be the same for each program run. I figured each compilation unit might have it's own gen variable, so I tested this theory by putting an int variable t, and change it, but t persists it's value across cpp files, and does not reset to 45, so why doesn't gen?

//Random.hpp
#pragma once
#include <random>
class Random
{
public:
    static void seed();
    static int getRandom(int minInclusive, int maxInclusive);
private:
    //static int t;
    static std::default_random_engine gen;
    static std::uniform_int_distribution<int> ints;
};

//Random.cpp
#include "Random.hpp"
#include <time.h>
//int Random::t = 45;
std::default_random_engine Random::gen;
std::uniform_int_distribution<int> Random::ints;
std::uniform_real_distribution<float> Random::floats;
void Random::seed()
{
    //t = 0;
    gen.seed(static_cast<unsigned int>(time(NULL)));
}
int Random::getRandom(int minInclusive, int maxInclusive)
{
    //return t++;//t persists it's value, but gen seems to lose it's seed
    std::uniform_int_distribution<int>::param_type range(minInclusive, maxInclusive);
    ints.param(range);
    return ints(gen);
}




Aucun commentaire:

Enregistrer un commentaire