In this article we will discuss how to capture local variables from outer scope in Lambda.

A simple Lambda syntax is,

Local variables from outer scope can be captured inside Lambda in 2 modes i.e.

  1. By Value
  2. By Reference

Capturing Local Variables by value inside Lambda Function

To capture the local variables by value, specify their name in capture list i.e.

Now, the variables specified in capture list will be copied inside lambda by value. Inside lambda they can be accessed but can not be changed, because they are const.

To modify the we need to add mutable keyword i.e.

Now the captured variables can be modified. But their modification will not affect value of outer scope variables, because they are captured by value.

Checkout this example,

Output:

Capturing Local Variables by Reference inside Lambda

To capture the local variables by reference, specify their name in capture list with prefix & i.e.

Now, the variables specified in capture list will be captured inside lambda by Reference. Inside lambda they can be accessed and their value can also be changed. Also, their modification will affect value of outer scope variables, because they are captured by Reference.

Checkout this example,

Output:

Capture All Local Variables from outer scope by Value

To capture all local variables from outer scope by value, pass “=” in the capture list i.e.

Capture all local variables from outer scope by Reference

To capture all local variables from outer scope by Reference, pass “&” in the capture list i.e.

Mixing capturing by value and Reference

We can also mix the capturing mode of Lambda by passing some local variables by value and some by reference i.e.

Be-aware of capturing local variables by Reference in Lambda

If in lambda we are capturing local variables by reference, then we need to make sure that when lambda function is accessed or called, then all the by reference captured local variables are still in scope.

If lambda will try to access or modify a by reference captured local variable, which is not in scope anymore i.e. which has been destroyed due to stack unwinding, then crash can happen.

Checkout this example,

Output

Here we tried to accessed the variable that has already been destructed due to stack unwinding.

To compile the above examples in linux use following command,

g++ –std=c++11 example.cpp

Click Here to Subscribe for more Articles / Tutorials like this.