title: Moving a lambda: once you've move-captured a move-only type, how can the lambda be used?
body: <p><a href="https://stackoverflow.com/a/20669290/1858225">This answer</a> explains how to move-capture a variable within a lambda in C++14.</p>
  
  <p>But once you've move-captured an un-copyable object (such as a <code>std::unique_ptr</code>) within a lambda, you cannot copy the lambda itself.</p>
  
  <p>This would be fine if you could <em>move</em> the lambda, but I get a compile error when trying to do so:</p>
  
  <pre><code>using namespace std;
  
  class HasCallback
  {
    public:
      void setCallback(std::function&lt;void(void)&gt;&amp;&amp; f)
      {
        callback = move(f);
      }
  
      std::function&lt;void(void)&gt; callback;
  };
  
  int main()
  {
    auto uniq = make_unique&lt;std::string&gt;("Blah blah blah");
    HasCallback hc;
    hc.setCallback(
        [uniq = move(uniq)](void)
        {
          std::cout &lt;&lt; *uniq &lt;&lt; std::endl;
        });
  
    hc.callback();
  }
  </code></pre>
  
  <p>This produces the following error with <code>g++</code> (I've attempted to copy only the relevant line):</p>
  
  <pre><code>error: use of deleted function ‘main()::&lt;lambda()&gt;::&lt;lambda&gt;(const main()::&lt;lambda()&gt;&amp;’
  </code></pre>
  
  <p>...implying, I think, that my attempt to move the lambda has failed.</p>
  
  <p><code>clang++</code> gives a similar error.</p>
  
  <p>I tried explicitly <code>move</code>ing the lambda (even though it's a temporary value), but that did not help.</p>
  
  <p><strong>EDIT:</strong> The answers below adequately address the compile errors produced by the above code. For an alternate approach, simply <code>release</code> the unique pointer's target value into a <code>std::shared_ptr</code>, which <em>can</em> be copied. (I'm not writing this as an answer, because that would assume that this is an XY problem, but the underlying reason why <code>unique_ptr</code> can't be used in a lambda that gets converted to a <code>std::function</code> is important to understand.)</p>
  
  <p><strong>EDIT 2:</strong> Hilariously enough, I just realized <code>auto_ptr</code> would actually do the right thing here (!), as far as I can tell. It acts essentially like <code>unique_ptr</code>, but allows copy-construction in place of move-construction.</p>