Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing by value in recursive lambda

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.

like image 724
Dinesh Maurya Avatar asked Jan 04 '23 08:01

Dinesh Maurya


1 Answers

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.

like image 146
Angew is no longer proud of SO Avatar answered Jan 09 '23 19:01

Angew is no longer proud of SO