捕获示例
int i = 0;
int j = 0;
auto f = [t1 = i, &t2 = j]() {};
mutable
代码
int main() {
int a = 0;
auto fun1 = [=]() mutable {
a = 1;
return a;
};
std::cout << "fun1-test:" << std::endl;
std::cout << fun1() << std::endl;
std::cout << a << std::endl;
auto fun2 = [=]() {
// 编译错误:表达式必须是可修改的左值
// a = 2;
return a;
};
std::cout << "fun2-test:" << std::endl;
std::cout << fun2() << std::endl;
std::cout << a << std::endl;
auto fun3 = [&]() mutable {
a = 3;
return a;
};
std::cout << "fun3-test:" << std::endl;
std::cout << fun3() << std::endl;
std::cout << a << std::endl;
auto fun4 = [&]() mutable {
a = 4;
return a;
};
std::cout << "fun4-test:" << std::endl;
std::cout << fun4() << std::endl;
std::cout << a << std::endl;
return system("pause");
}
输出结果
fun1-test:
1
0
fun2-test:
0
0
fun3-test:
3
3
fun4-test:
4
4
注意事项
- 不要用引用捕获局部变量。
- lambda不需要捕获静态变量就可以直接使用。
- 每一个lambda都是独一无二的类型。
- 虽然不能按值捕获数组,但是可以改用std::array。