Dinesh Maurya Dinesh Maurya - 3 years ago 170
C++ Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download