Using C++11 lambdas asynchronously, safely

后端 未结 3 1424
失恋的感觉
失恋的感觉 2021-01-31 11:06

I\'ve come to C++11 from an Objective-C background, and one thing I\'m struggling to come to terms with is the different capturing semantics of C++11 lambdas vs Objective-C \"bl

3条回答
  •  半阙折子戏
    2021-01-31 11:53

    Actually, there's one right answer to this problem. The answer has the exact same effect of binding with shared_from_this() (like when you do it with boost::asio::io_service). Think about it; what does binding with shared_from_this() do? It simple replaces this. So what prevents you from replacing this with shared_from_this() totally?

    Following your example, which I updated to make the difference clearer, instead of this:

    auto strongThis = shared_from_this();
    
    doSomethingAsynchronously([strongThis, this] () {
      this->someMember_ = 42; //here, you're using `this`... that's wrong!
    });
    

    Do this:

    auto strongThis = shared_from_this();
    
    doSomethingAsynchronously([strongThis] () //notice, you're not passing `this`!
    {
      strongThis->someMember_ = 42;            
    });
    

    The only cost here is that you're gonna have to prefix everything with strongThis->. But this is the most meaningful way to do it.

提交回复
热议问题