简体   繁体   English

lambda捕获成员变量由此

[英]lambda capture member variable by this

To capture a member data in object, the lambda need capture 'this' pointer: 要捕获对象中的成员数据,lambda需要捕获“ this”指针:

class A {
public:
    void func() {
       auto f = [this](){_b->do_something();};
       _c->run(f); // asynchronized method
    }
private:
    B* _b;
    C* _c;
};

There is a problem: when f gets called by _c, object of A may be destory! 有一个问题:当_c调用f时,A的对象可能是虚构的! Will _b->do_something(); _b->do_something(); become an undefined behavior? 变成不确定的行为?

Make use of a shared_ptr , and then capture that in the lambda. 利用shared_ptr ,然后在lambda中捕获它。 Now when you create the instance of A you will need to do so with make_shared . 现在,当您创建A的实例时,您需要使用make_shared来完成。 It's best if you inherit from enable_shared_from_this and then you can use shared_from_this in the lambda capture to force the A to stay around for long enough for the lambda to run without needing to have a reference to the shared_ptr anywhere else. 如果你继承这是最好enable_shared_from_this ,然后你可以使用shared_from_this在lambda捕获迫使A呆在身边的足够长的lambda来,而不需要具有对一个给定运行shared_ptr其他地方。

The first part of your class will look something like this: 您课程的第一部分将如下所示:

class A : std::enable_shared_from_this<A> {
public:
    void func() {
       auto self = shared_from_this();
       auto f = [this, self](){_b.do_something();};
       _c->run(f); // asynchronized method
    }

From 3.8 Object life 从3.8对象生命

  1. [...] after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object will be or was located may be used but only in limited ways. [...]在对象的生存期结束之后,在重新使用或释放​​对象所占用的存储空间之前,可以使用任何指向该对象将要或将要位于的存储位置的指针,但只能以有限的方式使用。 [...] The program has undefined behavior if: [...]该程序在以下情况下具有未定义的行为:

[...] [...]

5.2 the pointer is used to access a non-static data member or call a non-static member function of the object 5.2指针用于访问对象的非静态数据成员或调用非静态成员函数

So yes, using pointer to B in destroyed A is UB. 所以是的,在已破坏的A中使用指向B的指针是UB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM