Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Lambdas: capture list vs. parameter list

Tags:

c++

c++11

lambda

According to the C++11 standard, lambda expressions may use variables in the enclosing scope, by means of the capture list, the parameter list or both.

So, let's look to two versions of the same code.

1) With capture

int x = 4;  cout << "With capture  : Factorial of " << x << " = " << [x]() // <= Capture {     int r = 1;     for (int i = x; i > 1; i--) r = r * i;     return r; }() << endl; 

2) With parameter

int x = 4;  cout << "With parameter: Factorial of " << x << " = " << [](int x) // <= Parameter {     int r = 1;     for (int i = x; i > 1; i--) r = r * i;     return r; }(x) << endl; 

The output is:

With capture  : Factorial of 4 = 24 With parameter: Factorial of 4 = 24 

Since we can pass parameters to lambdas in the parameter list (just as with any C++ function), why do we need the capture list?

Can someone show me cases where parameter list doesn't work and only capture list does?

like image 981
Xico d'Abrolha Avatar asked Feb 23 '15 08:02

Xico d'Abrolha


People also ask

What is a lambda capture list?

The capture clause is used to (indirectly) give a lambda access to variables available in the surrounding scope that it normally would not have access to. All we need to do is list the entities we want to access from within the lambda as part of the capture clause.

What is capture list in lambda C++?

The capture list defines the outside variables that are accessible from within the lambda function body. The only capture defaults are. & (implicitly capture the used automatic variables by reference) and. = (implicitly capture the used automatic variables by copy).

What does it mean to lambda capture this?

The lambda is capturing an outside variable. A lambda is a syntax for creating a class. Capturing a variable means that variable is passed to the constructor for that class. A lambda can specify whether it's passed by reference or by value.

Does lambda capture reference by value?

Lambdas always capture objects, and they can do so by value or by reference.


1 Answers

For example using stl algorithms:

std::vector<int> items; int factor; auto foundItem = std::find_if(items.begin(), items.end(),  [&factor](int const& a)  {     return a * factor == 100;  }); 

In this case you're called in the lambda for every item in the container and you return if the value multiplied by a captured factor is 100. The code doesn't make much sense, it's just to show you an example where capture and parameter lists matter.

like image 81
dau_sama Avatar answered Sep 25 '22 22:09

dau_sama