title: Objective-C blocks and C++ objects
body: <p>I have a method that is being executed on a background thread.  From that method I'm trying to <code>dispatch_async</code> a block on the main thread.  The block uses a local C++ object which is supposed to be copy constructed according to the <a href="http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html#//apple_ref/doc/uid/TP40007502-CH6-SW5">Apple reference</a>.  I'm getting a segmentation fault and from the trace I see that something very sketchy is going on.  Here's the simplified version of my code.</p>
  
  <pre><code>struct A
  {
      A() { printf("0x%08x: A::A()\n", this); }
      A(A const &amp;that) { printf("0x%08x: A::A(A const &amp;%p)\n", this, &amp;that); }
      ~A() { printf("0x%08x: A::~A()\n", this); }
      void p() const { printf("0x%08x: A::p()\n", this); }
  };
  
  - (void)runs_on_a_background_thread
  {
      A a;
      a.p();
      dispatch_async(dispatch_get_main_queue(), ^{
          printf("block begins\n");
          a.p();
          printf("block ends\n");
      });
  }
  </code></pre>
  
  <p>And this is the output:</p>
  
  <pre><code>0xbfffc2af: A::A()
  0xbfffc2af: A::p()
  0xbfffc2a8: A::A(A const &amp;0xbfffc2af)
  0x057ae6b4: A::A(A const &amp;0xbfffc2a8)
  0xbfffc2a8: A::~A()
  0xbfffc2af: A::~A()
  0xbfffdfcf: A::A(A const &amp;0x57ae6b4)
  0xbfffdfcf: A::~A()
  block begins
  0xbfffdfcf: A::p()
  block ends
  0x057ae6b4: A::~A()
  </code></pre>
  
  <p>There are two things that I don't understand.  The first one is why by the time it gets to <code>0xbfffdfcf: A::p()</code> the destructor on that object has been called already.</p>
  
  <p>The second thing I'm struggling with is why there are so many copy constructors being called.  I expect one.  That should happen when a copy of <code>a</code> is created to be captured by the block.</p>
  
  <p>I'm using Xcode 3.2.5 with GCC.  I experience the same behavior on the simulator and on the device.</p>