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?
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With