title: Lambda capturing this and long-running function
body: <p>I have a function that takes a long time to run, but thankfully it runs asynchronously.  I want to take the result of this function call and set it to a class instance's private variable.  Seems easy:</p>
  
  <pre><code>// Exists in some other library.
  void LongRunningAsync(std::function&lt;void(int)&gt; callback) {
    sleep(10);
    callback(5);
  }
  
  class A {
   public:
    void Do() {
      auto lambda = [this](int val) {
        // Some processing...
        var_ = val;
      };
      LongRunningAsync(lambda);
    }
  
   private:
    var_;
  };
  
  int main() {
    A* a = new A;
    a-&gt;Do();
    // Wait for LongRunningAsync to finish.
    sleep(20);
    return 0;
  }
  </code></pre>
  
  <p>The problem is adding the following line to <code>main</code>, right before the comment:</p>
  
  <pre><code>delete a;
  </code></pre>
  
  <p>Now when <code>LongRunningAsync</code> invokes the callback, it will attempt to modify a member variable of a deleted instance (which is UB).</p>
  
  <p>Is there a way to salvage this approach? I've recently learned about the following solution:</p>
  
  <pre><code>void LongRunningAsync(std::function&lt;void(int)&gt; callback) {
    sleep(10);
    callback(5);
  }
  
  class A : public std::enable_shared_from_this&lt;A&gt; {
   public:
    void Do() {
      std::weak_ptr&lt;A&gt; weak = shared_from_this();
      auto lambda = [weak](int val) {
        auto shared = weak.lock();
        if (!shared) return;
        // Some processing...
        shared-&gt;var_ = val;
      };
      LongRunningAsync(lambda);
    }
  
   private:
    var_;
  };
  
  int main() {
    auto a = std::make_shared&lt;A&gt;();
    a-&gt;Do();
    // Wait for LongRunningAsync to finish.
    sleep(20);
    return 0;
  }
  </code></pre>
  
  <p>But it requires changing <strong>all</strong> <code>A</code> variables to shared_ptr.  Is there a less intrusive way to make this work?</p>