The class montecarlo
contains lambda as a member variable. This code can be compiled, but will cause "Segmentation fault(core dumped)" in run time. Could you explain how to fix it?
#include<random>
#include<functional>
#include<iostream>
class montecarlo
{
public:
montecarlo(double x_min, double x_max);
std::function<double()> rand;
};
montecarlo::montecarlo(double x_min, double x_max){
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> rand_(x_min, x_max);
rand = [&](){return rand_(mt);};
}
int main(){
montecarlo x(0, 1);
std::cout<<x.rand()<<std::endl;
}
And what made me wonder is when I change the constructor's implementation into the code below, it worked:
montecarlo::montecarlo(double x_min, double x_max){
rand = [](){return 0;};
}
You would probably know, but let me say that what I want to do is not just using a random functions.
You're trying to capture rand_
and mt
by reference; they're local objects inside montecarlo::montecarlo
, when lambda is called outside montecarlo::montecarlo
these local objects have been destroyed and the references stored in lambda object have become dangled.
You could change it to capture by copy; and note you need to make the lambda mutable
to make the invocation on rand_
valid. e.g.
rand = [=]() mutable {return rand_(mt);};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With