A lambda function which is a member variable crashes

  • A+

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 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);}; 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: