"Capture" in a lambda expression - C++
A lambda expression is an anonymous, inline function. It is used to create a local function, mainly for passing as an argument to a function call or as a return value.
"Capture" makes variables in the local scope available for use in the body of the lambda expression. By default, variables are captured by value. Variables can be captured by the reference as well. Also, there are syntaxes which allow passing all the local variables and objects into the lambda expression.
2. What is a
lambda
expression
A lambda expression is an
anonymous, inline function.
It is used to create a local
function, mainly for passing as
an argument to a function call
or as a return value.
4. "Capture" in
a lambda
expression
Capture makes variable in the local scope
available for use in the body of the lambda
expression.
Write the name of the desired variable inside
[] of the lamda expression.
By default, variables are captured by value.
5. "Capture" in
a lambda
expression
Capture by value
#include <iostream>
using namespace std;
int main()
{
int x{10};
auto func = [x]()
{
cout << x << endl;
};
func();
}
Output: 10
6. "Capture" in
a lambda
expression
Capture by reference
#include <iostream>
using namespace std;
int main()
{
int x{10};
auto func = [&x]()
{
x++;
};
func();
cout << x << endl;
}
Output: 11
7. "Capture" in
a lambda
expression
To capture all local variables by value
#include <iostream>
using namespace std;
int main()
{
int x{10}, y{20};
auto func = [=]()
{
cout << x << " " << y << endl;
};
func();
}
Output: 10 20
8. "Capture" in
a lambda
expression
To capture all local variables by reference
#include <iostream>
using namespace std;
int main()
{
int x{10}, y{20};
auto func = [&]()
{
x++; y++;
};
func();
cout << x << " " << y << endl;
}
Output: 11 21
9. "Capture" and
objects
Lambda expressions can be used in a member
function to capture the data members of the
object.
The data members are captured through a
reference to the object.
10. "Capture" and
objects
#include <iostream>
using namespace std;
class Student
{
public:
int age{ 10 };
public:
void printAge()
{
auto lambdaAge = [this]()
{
cout << age << endl;
};
lambdaAge();
}
};
int main()
{
Student s;
s.printAge();
}
Output: 10