lambda允许捕捉对象的this指针,但是当多线程处理或者离开作用域等原因,对象的生命期已经结束的情况下,还继续访问lambda函数就会可能会造成比较严重的问题:
#include <iostream>
using namespace std;
class A{
public:
A()
{
cout<<"construct this:"<<this<<endl;
}
A(const A& a)
{
cout<<"copy construct this:"<<this<<endl;
}
~A()
{
data = 6;
cout<<"destruct this:"<<this<<endl;
}
auto func()
{
auto f = [this]()
{
cout<<"this addr:"<<this<<" data:"<<this->data<<endl;
};
return f;
}
int data{8};
};
auto t()
{
A a1;
cout<<"a1 addr:"<<&a1<<endl;
return a1.func();
}
int main(){
auto doF = t();
doF();
return 0;
}
运行程序输出:
construct this:0x63fdcc //函数t中a1构造
a1 addr:0x63fdcc
destruct this:0x63fdc