本文参考了侯捷老师的关于《C++标准11-14》的讲义。
capture的传值和传引用的区别
#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;
}
执行结果
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;
}
执行结果
id: 42
id: 43
id: 44
45
capture与外部静态变量
- 外部静态变量要先于lambda表达式出现,才能在lambda表达式内部使用。
- lambda内部变量不能在外部区域使用。
#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;
}
执行结果:
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.