Quick summary ↬ A lambda function is an anonymous function that can be defined inline without a separate function declaration. It allows you to create small, local functions with captured variables and can be used in situations where a function object or function pointer is expected. Lambdas are especially useful in scenarios where you need to pass a function as an argument or when you want to define a function inside another function.
How to pass reference to a lambda in C++
[&]() { /* code */ }
- This is what we are going to discuss in this blog post.
Let’s break down the syntax:
-
[&]
is the lambda capture list. It specifies which variables from the enclosing scope are captured by reference. In this case, the lambda captures all variables by reference, allowing you to access and modify the variables from the enclosing scope within the lambda body. -
()
represents the parameter list of the lambda function. It can be empty if the lambda doesn’t take any parameters. If parameters are specified, they are enclosed within the parentheses. -
{ /* code */ }
is the lambda body. It contains the actual code that gets executed when the lambda function is invoked. You can put any valid C++ code inside the lambda body. -
By using
&
as the lambda capture list, you are capturing variables by reference, allowing the lambda function to access and modify the variables from the enclosing scope. This way, you can pass variables into the lambda and have them available for use within the lambda body.
Here’s an example to illustrate the usage:
|
|
Output:
|
|
In this example, the lambda function captures the variable x by reference ([&])
, allowing it to modify the value of x within the lambda body. The value of x
is increased by 5 inside the lambda, and the modified value is printed. Outside the lambda, the value of x
remains modified.
I hope this explanation clarifies the usage of [&]() { /* code */ }
in C++ lambda functions. Let me know if you have any further questions!