title: What is the lifetime of a C++ lambda expression?
body: <p>(I have read <a href="https://stackoverflow.com/questions/5207467/what-is-lifetime-of-lambda-derived-implicit-functors-in-c">What is the lifetime of lambda-derived implicit functors in C++?</a> already and it does not answer this question.)</p>
  
  <p>I understand that C++ lambda syntax is just sugar for making an instance of an anonymous class with a call operator and some state, and I understand the lifetime requirements of that state (decided by whether you capture by value of by reference.) But what is the lifetime of the lambda object itself? In the following example, is the <code>std::function</code> instance returned going to be useful?</p>
  
  <pre><code>std::function&lt;int(int)&gt; meta_add(int x) {
      auto add = [x](int y) { return x + y; };
      return add;
  }
  </code></pre>
  
  <p>If it is, <em>how does it work</em>? This seems a bit too much magic to me - I can only imagine it working by <code>std::function</code> copying my whole instance, which could be very heavy depending on what I captured - in the past I've used <code>std::function</code> primarily with bare function pointers, and copying those is quick. It also seems problematic in light of <code>std::function</code>'s type erasure.</p>