title: Double free when using lambda to function pointer cast
body: <p>After spending many days debugging a very obscure error in a complicated program, I finally reduced the problem to a very simple, reproducible scenario. </p>
  
  <p>Basically, it appears that if I have a simple non-capturing lambda with a signature that takes a single argument by value (and returns an object by value), and I convert that lambda to an equivalent function pointer type and then invoke the function pointer, the destructor of the object passed as an argument is incorrectly invoked.  </p>
  
  <p>Here's a simple reproducible case that shows the problem, and causes a double-free using GCC 4.9.2:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;memory&gt;
  #include &lt;utility&gt;
  #include &lt;cassert&gt;
  
  struct Foo
  {
      Foo() = default;
      Foo(const Foo&amp;) = delete;
      Foo&amp; operator = (const Foo&amp;) = delete;
  
      ~Foo()
      {
          std::cout &lt;&lt; "Destroying object " &lt;&lt; this &lt;&lt; std::endl;
      }
  };
  
  auto callback = [](std::unique_ptr&lt;Foo&gt; p)
  {
      assert(p);
      return p;
  };
  
  int main()
  {
      std::unique_ptr&lt;Foo&gt; ptr(new Foo());
      auto fptr = static_cast&lt;std::unique_ptr&lt;Foo&gt;(*)(std::unique_ptr&lt;Foo&gt;)&gt;(callback);
      auto result = fptr(std::move(ptr));
  }
  </code></pre>
  
  <p>The intended behavior of this program is to allocate a unique instance of <code>Foo</code> managed by a <code>unique_ptr</code>.  Then move that instance once by passing it as an argument to <code>callback</code>, then move the instance again when <code>callback</code> returns it by value, and finally destruct the instance.  (Granted the compiler may also remove at least one of the move constructor calls using copy-elision, but that's not important here.)</p>
  
  <p>So therefore I should really only see <code>Foo</code>'s destructor called once.</p>
  
  <p>Instead I see this when I run this program:</p>
  
  <pre><code>Destroying object 0xdf4410
  Destroying object 0xdf4410
  *** Error in `./test9': double free or corruption (fasttop): 0x0000000000df4410 ***
  </code></pre>
  
  <p>Somehow, the compiler is generating code that incorrectly invokes the <code>unique_ptr</code> destructor when it is passed to <code>callback</code>.</p>
  
  <p>Note that this <em>only</em> happens if I convert the non-capturing lambda to an equivalent function pointer.  If I invoke <code>callback</code> directly, there is no problem.</p>
  
  <p>So I can't see why this would happen, and therefore I am asking if this is likely a compiler bug with lambda to function pointer conversion, or if I am just doing something wrong here.</p>