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 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
this
in lambda body has any difference?
Jan 14, 2014 at 3:06
this
because this
is always captured 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.
The first question JaredPar already answered.
For your second quesiton, the this in lambda body is same as the this of its containing class. The following example is from standard.
struct S1 {
int x, y;
int operator()(int);
void f() {
[=]()->int {
return operator()(this->x + y);
// equivalent to S1::operator()(this->x + (*this).y)
// this has type S1*
};
}
};