title: Copy-assigning C++ lambdas of the same type
body: <p>C++ lambdas have a deleted copy-assignment operator. I don't know why. However that limitation can be easily worked around. But I don't feel good about it. What could be wrong with the following approach? <a href="https://wandbox.org/permlink/zmqJKDtsuxYgDI2l" rel="nofollow noreferrer">Live code</a>.</p>
  
  <pre><code>template &lt;class T&gt; void assign(T&amp; dest, T&amp;&amp; val)  { 
    dest.~T();   
    new (&amp;dest) T(std::forward&lt;T&gt;(val)); 
  }
  
  auto make_lambda(int i) {   
    return [v=std::make_shared&lt;int&gt;(i)] {std::cout &lt;&lt; *v &lt;&lt; "\n"; }; 
  }
  
  int main() {  
    auto one = make_lambda(1);   
    assign(one, make_lambda(2));   
    one();  // prints 2 
  }
  </code></pre>
  
  <p>There are possibly two reasons I can think of:</p>
  
  <ol>
  <li>Construction may throw and <code>dest</code> main remain uninitialized and destroyed again later in main. Double deletion.</li>
  <li>Destructor may throw if some badly written library throws in a destructor. </li>
  </ol>
  
  <p>Exception during construction can be worked-around too with strong exception safety guarantee. Consider <code>assignv2</code>:</p>
  
  <pre><code>template &lt;class T&gt;
  void assignv2(T&amp; dest, const T&amp; src) 
  {
    static std::allocator&lt;T&gt; alloc;
    static typename std::aligned_storage&lt;sizeof(T), alignof(T)&gt;::type storage;
    std::memcpy(&amp;storage, &amp;dest, sizeof(T));
    try {
      new (&amp;dest) T(src);
    }
    catch(...) {
      std::memcpy(&amp;dest, &amp;storage, sizeof(T));
      throw;
    }
    reinterpret_cast&lt;T*&gt;(&amp;storage)-&gt;~T();
  }
  </code></pre>