lambda允许捕捉对象的this指针,但是当多线程处理或者离开作用域等原因,对象的生命期已经结束的情况下,还继续访问lambda函数就会可能会造成比较严重的问题:
#include using namespace std;class A{
public:A(){cout<<"construct this:"<data<
运行程序输出:
construct this:0x63fdcc //函数t中a1构造
a1 addr:0x63fdcc
destruct this:0x63fdcc //函数t离开作用域,a1析构
this addr:0x63fdcc data:6 //doF调用lambda函数f访问了已经析构了的a1对象
可见在对象a1已经析构的情况下,函数doF(也就是lambda函数f)还是访问了a1的地址空间,这是很危险的操作。
C++17新增了捕获this副本,可以解决这个问题:
#include using namespace std;class A{
public:A(){cout<<"construct this:"<data<
运行程序输出:
construct this:0x63fdbc //函数t中a1构造
a1 addr:0x63fdbc
copy construct this:0x63fd6c //函数t中return a1.func,会拷贝构造一个新的临时对象tmp1
copy construct this:0x63fe0c //auto doF = t();会拷贝构造一个新的临时对象tmp2
destruct this:0x63fd6c //tmp1析构
destruct this:0x63fdbc //a1析构
this addr:0x63fe0c data:8 //在临时对象tmp2上调用函数doF
destruct this:0x63fe0c //临时对象tmp2析构