Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A lambda function which is a member variable crashes

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.

like image 423
orematasaburo Avatar asked Jul 03 '18 07:07

orematasaburo


1 Answers

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);};
like image 110
songyuanyao Avatar answered Oct 07 '22 00:10

songyuanyao