title: How to implement a method that creates a recursive lambda and returns it
body: <p>I found a post on how to <a href="https://stackoverflow.com/questions/2067988/">create a recursive lambda</a>, but it is not clear how to return it from a function.</p>
  <p>As far as I see, in the code below, captured <code>func</code> refers to a destroyed object:</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;functional&gt;
  
  std::function&lt;int (int)&gt; make_lambda()
  {
      std::function&lt;int (int)&gt; func;
      
      func = [&amp;func](int val)
      {
          if (val &lt; 10)
          {
              return func(val + 1);
          }
          
          return val;
      };
      
      return func;
  }
  
  int main()
  {
      std::cout &lt;&lt; make_lambda()(0);
      
      return 0;
  }
  </code></pre>
  <p>How to make this code work?</p>
  <p>Is there a better way than using <code>std::shared_pointer&lt;std::function&lt;int (int)&gt;&gt;</code>?</p>
  <p><code>void make_lambda(std::function&lt;int (int)&gt;&amp;)</code> is not an option.</p>
  <p><strong>EDIT1:</strong></p>
  <p>Why is there no <code>this</code> allowing lambdas to refer to themselves?</p>