I have a program containing multiple classes, some of which require random doubles and ints. In one of the classes, I defined a struct to seed the random engine and be able to generate random reals and ints through an object of that struct whenever I need one. The .hpp file with class and struct declations looks like this:
struct RNG {
public:
static std::mt19937 gen;
static std::uniform_int_distribution<uint32_t> dist_ui;
static std::uniform_real_distribution<double> dist_d;
uint32_t r_ui = dist_ui(gen);
double r_d = dist_d(gen);
private:
static unsigned seed;
};
class A {
private:
uint32_t a_;
public:
A();
};
The .cpp file looks like this:
#include "A.hpp"
unsigned RNG::seed = 42;
std::mt19937 RNG::gen(RNG::seed);
std::uniform_int_distribution<uint32_t> RNG::dist_ui(1, std::numeric_limits<uint32_t>::max());
std::uniform_real_distribution<double> RNG::dist_d(0.0,1.0);
A::A() {
RNG* r;
a_ = r->dist_ui(r->gen);
}
Now, if I call uniform_real_distribution with
r->dist_d(r->gen)
everthing works fine. However, if I call uniform_int_distribution with
r->dist_ui(r->gen)
as in the above snippet, I get a segmentation fault. The error also occurs if I define my struct only with int dist instead of both real and int, or if I change the boundaries of the int dist to [0,100) or whatever. Does anyone have a clue what happens here? I appreciate any help!
EDIT: I get the same error if I access the non-static members like this
RNG r;
a_ = r.r_ui;