title: Storing C++ Lambda in a member variable to be used as a callback?
body: <p>I'm trying to implement a c++ function that gets a Lambda callback as a parameter. The thing is, the callback is initiated asynchronously from another function in the same (called) class. I therefore need to store the Lambda in a member variable so that it can be accessed by the asynchronous function that needs to initiate the callback.</p>
  
  <p>I tried all the ways I could think of to declare, set and call the Lambda using a member variable, but the code always crashes either in the assignment or in the call.</p>
  
  <p>Here's a stripped-out version of what I'm trying to do.</p>
  
  <p>Declaring the function:</p>
  
  <pre><code>void function(const std::function&lt;void()&gt;callback);
  </code></pre>
  
  <p>Calling the function from the main code:</p>
  
  <pre><code>myClass-&gt;function([](){cout &lt;&lt; "Callback called";});
  </code></pre>
  
  <p>If I execute <code>callback</code> from within <code>function</code> it works fine, but I couldn't find a way to store it in a member variable (e.g. <code>m_callback</code>) and invoke it from another function of the same class.</p>