This article refers to teacher Hou Jie's lecture notes on "C++ Standard 11-14".
The difference between capture by value and by reference
#include <iostream>
using namespace std;
int main()
{
int id = 0;
auto f = [id] () mutable {
cout << "id: " << id << endl;
++id;
};
id = 42;
f();
f();
f();
cout << id << endl;
return 0;
}
Results of the
id: 0
id: 1
id: 2
42
#include <iostream>
using namespace std;
int main()
{
int id = 0;
auto f = [&id] () mutable {
cout << "id: " << id << endl;
++id;
};
id = 42;
f();
f();
f();
cout << id << endl;
return 0;
}
Results of the
id: 42
id: 43
id: 44
45
Capture and external static variables
- The external static variable must appear before the lambda expression before it can be used inside the lambda expression.
- Lambda internal variables cannot be used in external areas.
#include <iostream>
using namespace std;
int main()
{
static int id = 5;
// 外部静态变量要先于lambda表达式出现,才能在lambda表达式内部使用。
auto f = [] () mutable {
cout << "id: " << id++ << endl;
static int id2 = 10;
cout << "id2: " << id2++ << endl;
};
id = 42;
f();
f();
f();
cout << id << endl;
// cout << "id2: " << id2 << endl;
// 编译不通过,error: 'id2' was not declared in this scope; did you mean 'id'?
return 0;
}
Results of the:
id: 42
id2: 10
id: 43
id2: 11
id: 44
id2: 12
45
lambda的capture
- [=] means that the outer scope is passed to the lambda by value.
- [&] means that the outer scope is passed to the lambda by reference.
Ex:
int x=0;
int y=42;
auto qqq = [x, &y] {…};
[=, &y] to pass y by reference and all other object by value.