This question already has an answer here:
I have a situation in which I'd like to have function called inside a lambda function.
Below I put a simplification of the situation:
method A1 get a function pointer f as argument and each time add a lambda function to a queue where inside there is the call to a method of the same class but with the parameter that is the result of the call of the function f.
Obviously f does not return always the same value.
//class A
method A1(int (*f)(void)){
auto lambda = [&,f]()->bool{
A3(f); //<—
return true;
});
event.add(lambda); //event instance of class B
}
method A2(){
func = event.getNextEvent();
func();
}
methodA3(int (*f)(void)){
for(int i=0;i<1000;i++)std::cout<<f()<<std::endl;
}
//class B
add()
When I execute the code with f() I have segmentation fault, like if the reference is "lost". Without adding f() as parameter to A3 the code works fine.
edit
I have edited the code in the following way, but now I get a strage behavior, f is a function that returns a random value with a defined distribution, but the value printed in the example is always the same
Aucun commentaire:
Enregistrer un commentaire