7-2 捕获列表

7.2 捕获列表

7.2.1 作用域

注意:被捕获的变量必须是一个自动变量(即非静态的局部变量)。而下面的变量,无须捕获即可被使用:

  • 全局变量

  • 静态局部变量


下面的程序验证了无需捕获即可使用的变量是引用。而捕获的变量是常量,且值在lambda表达式定义的瞬间就已经确定。

#include <iostream>
using namespace std;

int x = 1;
int main()
{
int y = 0;
static int 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>

class A
{
public:
void print()
{
std::cout<<"class A"<<std::endl;
}

void test() //构建lambda,捕获this,并调用print和使用x
{
auto foo = [this]{
print();
x = 5;
}
foo();
}
private:
int x;
}

int main()
{
A a;
a.test();
}
2.【=】

​ 捕获所有值,包括this

#include <iostream>

int main()
{
int x = 5, y = 8;
auto foo = [=]{return x*y;};
std::cout<<foo()<<std::endl;
}
3.【&】

​ 捕获所有引用,包括this

#include <iostream>

int main()
{
int x = 5, y = 8;
auto foo = [&]{return x++*y++;};
for(int i = 0;i<10;i++)
std::cout<<foo()<<std::endl;
}