We can define recursive lambda function like
std::function<void(int)> fun = [&fun](int a) { if (a) fun(a - 1); };
then we can call it with
fun(10);
However if I change the definition to
std::function<void(int)> fun = [fun](int a) { if (a) fun(a - 1); };
and then try it to call with
fun(10);
segmentation fault occurs.
Can someone explain about why capture by reference works while capture by value gives segmentation fault.
Capture by value is evaluated as part of evaluating the lambda expression. At that time, fun
is still uninitialised, because you're still evaluating its initialiser. Only after that is fun
initialised, but by that time the copy has already happened.
The net effect is that the lambda function object stored inside fun
has a data member named fun
which is a copy of an uninitalised std::function
— Undefined Behaviour.
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