7-6 广义捕获(C++14)

7.6 广义捕获(C++14)

​ 在lambda表达式的简单捕获之外,还有广义捕获的方式,以自定义捕获的变量名和其初始值。

#include <iostream>
int main()
{
int x = 5;
auto foo = [y = x + 1]{ return y; };
std::cout<<foo()<<std::endl;
}

应用场景1:减少变量捕获所需要的开销(std::move)

#include <string>
#include <iostream>
int main()
{
std::string s = "hello world";
auto foo = [t = std::move(s)]
{ return t; };
std::cout << foo() << std::endl;
std::cout << s << std::endl;
}

应用场景2:异步调用时复制this指针,防止lambda表达式被调用时因原始this对象被析构造成未定义的行为

#include <iostream>
#include <future>

class Work
{
private:
int value;

public:
Work() : value(42) {}
std::future<int> spawn()
{
return std::async([=,tmp = *this] //捕获变量并拷贝自己的局部变量
{ return tmp.value; });
}
};

std::future<int> foo()
{
Work tmp;
return tmp.spawn();
}

int main()
{
std::future<int> f = foo();
f.wait();
std::cout << f.get() << std::endl;
}