int x = 1; intmain() { int y = 0; staticint z = 0; auto foo = [y]{x++;z++; cout<<x<<z<<endl;}; //y++报错 for(int i = 0;i<10;i++) { foo(); cout<<x<<z<<endl; } }
7.2.2 捕获值和捕获引用
1.捕获值
默认捕获的是常量
值在lambda表达式定义的瞬间就已经确定
如果要捕获值,并将其作为lambda表达式的局部变量来使用,可以使用mutable关键字
auto foo = [x,y]() mutable { x++;y++; }; //()在mutable前不能省略
2.捕获引用
语法:
auto foo = [&x, &y]{ return x++ * y++; };
7.2.3 特殊的捕获方法
1.【this】
捕获this指针,用于使用this的成员。
#include<iostream>
classA { public: voidprint() { std::cout<<"class A"<<std::endl; } voidtest()//构建lambda,捕获this,并调用print和使用x { auto foo = [this]{ print(); x = 5; } foo(); } private: int x; }
intmain() { A a; a.test(); }
2.【=】
捕获所有值,包括this。
#include<iostream>
intmain() { int x = 5, y = 8; auto foo = [=]{return x*y;}; std::cout<<foo()<<std::endl; }
3.【&】
捕获所有引用,包括this。
#include<iostream>
intmain() { int x = 5, y = 8; auto foo = [&]{return x++*y++;}; for(int i = 0;i<10;i++) std::cout<<foo()<<std::endl; }