On 09/15/2009 12:35 PM, Chris Lattner wrote:
The second major feature of Blocks vs c++ lambdas is that they can be
"copied onto the heap". This allows things like "Grand Central Dispatch"
to work: you can write code that executes blocks asynchronously or on
other threads/work queues (after the function containing the block has
returned). A simple example is:

void print_on_different_thread(int X) {
  run_asynch(^{
    printf("Hi %d\n", X);
  });
}

With lambdas, the closure would be go out of scope when
print_on_different_thread returns, but blocks allows "run_asynch" to
extend the lifetime of the block.

The lambda equivalent would be

void print_on_different_thread(int X) {
  run_asynch([=]{
    printf("Hi %d\n", X);
  });
}

since X is captured by copy, run_asynch can do whatever it wants with the closure and not worry about the original X going away.

The only difference between blocks and lambdas here seems to be where you decide to copy the locals off the stack.

Jason

Reply via email to