Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference betwen [=] and [&] in lambda functions?

Tags:

c++

c++11

lambda

I was studying lambda function in c++11 recently. But I don't know if there is any difference between [=] and [&]. If there is, what the difference is?

And in these two situation, does this in lambda body has any difference?

like image 753
pktangyue Avatar asked Jan 14 '14 02:01

pktangyue


People also ask

What does [=] mean in C++ 14?

The [=] you're referring to is part of the capture list for the lambda expression. This tells C++ that the code inside the lambda expression is initialized so that the lambda gets a copy of all the local variables it uses when it's created.

What does [&] mean in C++?

It's a lambda capture list and has been defined in C++ from the C++11 standard. [&] It means that you're wanting to access every variable by reference currently in scope within the lambda function.

What is lambda in C++?

In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.


2 Answers

The difference is how the values are captured

  • & captures by reference
  • = captures by value

Quick example

int x = 1; auto valueLambda = [=]() { cout << x << endl; }; auto refLambda = [&]() { cout << x << endl; }; x = 13; valueLambda(); refLambda(); 

This code will print

1 13 

The first lambda captures x by value at the point in which valueLambda is defined. Hence it gets the current value of 1. But the refLambda captures a reference to the local so it sees the up to date value

like image 125
JaredPar Avatar answered Sep 22 '22 08:09

JaredPar


  • & means "capture by reference".
  • = means "capture by value".

I replied here because I want to point out one thing:

this pointer is always captured by value. In C++11, this means, that if you want to capture a copy of a variable in a class, such as this->a, it will always be captured by reference in practice. Why?

Consider:

[this]() { ++this->a; } 

this is captured by value, but this is a pointer, so a is referenced through this.

If you want a copy of a member variable, in C++11, do something like this:

auto copy = this->a; [copy]() mutable { ++copy; } 

Beware of this caveat, because it is not intuitive until you think of it.

like image 32
Germán Diago Avatar answered Sep 24 '22 08:09

Germán Diago