lambda允许捕捉对象的this指针,但是当多线程处理或者离开作用域等原因,对象的生命期已经结束的情况下,还继续访问lambda函数就会可能会造成比较严重的问题:
- #include
-
- using namespace std;
-
- class A{
- public:
- A()
- {
- cout<<"construct this:"<<this<
- }
- A(const A& a)
- {
- cout<<"copy construct this:"<<this<
- }
- ~A()
- {
- data = 6;
- cout<<"destruct this:"<<this<
- }
-
- auto func()
- {
- auto f = [this]()
- {
- cout<<"this addr:"<<this<<" data:"<<this->data<
- };
- return f;
- }
-
- int data{8};
- };
-
- auto t()
- {
- A a1;
- cout<<"a1 addr:"<<&a1<
- return a1.func();
- }
-
-
- int main(){
- auto doF = t();
- doF();
- return 0;
- }
运行程序输出:
construct this:0x63fdcc //函数t中a1构造
a1 addr:0x63fdcc
destruct this:0x63fdc
-
相关阅读:
Unity JobSystem使用及技巧
GeoSOS-FLUS未来土地利用变化情景模拟模型
数据结构与算法学习(day1)——简化版桶排序
Windows高效开发环境配置(一)
SQL入门
这3款免费的Word转PDF转换器软件,建议收藏使用
C++模板类用作参数传递
Java高级编程day22【谷】
ICG-PEG-NHS,吲哚菁绿-聚乙二醇-活性酯,ICG-PEG2000-NHS
洛谷 : P1020 [NOIP1999 普及组] 导弹拦截
-
原文地址:https://blog.csdn.net/jiemashizhen/article/details/127992237