際際滷

際際滷Share a Scribd company logo
"CAPTURE"
IN
LAMBDA
EXPRESSION
C++
Lahiru Dilshan
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.
Defining a
lambda
expression
auto func = []()
{
// function body
};
lambda introducer
parameter list
name
"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.
"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
"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
"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
"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
"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.
"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
STAY CALM
AND
KEEP CODING!
Lahiru Dilshan

More Related Content

"Capture" in lambda expression.