For a lambda function, if you have many variables to capture from the scope of the lambda definition, you can use the default capture
| Type | Capture Syntax | Captured Variable |
|---|---|---|
| default capture by value | [=] |
Access only inside the lambda. It cannot change even in the lambda. Think of this as pass-by-const-value. |
| default capture by reference | [&] |
Access and change inside the lambda and the main program. |
| mutable default capture by value | [=](/*...*/) mutable |
Access only inside the lambda. It can change, but only in the lambda. Think of this as pass-by-value. |
This example shows the variations and the possible effects on the capture variables:
You can use the mutable specifier to write to a captured variable inside the lambda definition with the default capture by value, i.e., [=]. See this in the example above. You can also use mutable with non-default lambda captures, i.e., where you pass individual variables.
From a design perspective, use these defaults only if you pass a high percentage of variables in scope (see Stamp Coupling). Otherwise, capture individual variables.
| Lambda | Explanation |
|---|---|
Default capture by value, but x by reference |
|
Default capture by reference, but y by value |
|
Default by value, x and z by reference |
|
Default by reference, x and y by value |
|
Default by value with mutable — can modify the copy of x, original unchanged |
|
mutable + mixed: x mutates the original via ref, y++ mutates only the local copy |
|
mutable + mixed: x mutates the original, y++ mutates the local copy |
|
Mix of default by value, ref capture of x, and init capture z initialized to x*2 at definition; mutable allows modifying value copies |