问题
EDIT EDIT: A minimal reproducible example worked fine, in the end, I resolved the problem by carefully rebuilding my program. Doing so, I found a wrong access of an std::vector, which was probably one of the reasons execution failed.
So, long story short: I meessed up my code and didn't look carefully enough before posting this question.
However, as pointed out in the comments, I should not access uninitialized pointers as I am doing in my snippet below (RNG* r) even if they're static. Instead, use the scope resolution operator (::)
a_ = RNG::dist_ui(RNG::gen)
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;
回答1:
I have a guess here. Is the object of type A also static/global? If so, maybe your problem is because the order of static initialization is not defined. So, you're accessing dist_ui before it's initialized.
Please post the rest of the code (the one that creates an instance of A) if it's not the case.
来源:https://stackoverflow.com/questions/58905407/segmentation-fault-with-stduniform-int-distribution