[cfe-dev] Blocks vs. C++ lambda's?

Cory Nelson phrosty at gmail.com
Thu Apr 30 09:16:13 PDT 2009


2009/4/30 Remy Demarest <psycho.hedgehog at me.com>:
> Hi,
>
> The non-serious answer would be: because the C++(0x) syntax sucks. :P
>
> And now the serious answer: from what I can tell, C++(0x) lambdas
> cannot be used outside of their declaration scope at least if it uses
> variables that are contained in the innermost block scope of its
> creation...
>
> Whereas Apple's blocks have a few advantages, first they have a simple
> syntax, their type declaration is very close from function pointers
> (you replace * by ^), second, you don't need to declare which
> variables from the enclosing scope you want to use inside your block...
> All of them can be used inside, in case you want to modify one of the
> captured variables, you need to add the __block type specifier in
> front of the variable declarations. This is the equivalent to the
> [&total]{ total += 5; } syntax that is used in C++'s lambdas, the
> reference & operator doesn't mean the same thing in C, and we need the
> blocks to be compatible with C.
>
> And most importantly, the best reason to prefer Apple's feature is
> that you can fully use the blocks outside of their declaration scope,
> even though the variables (__block or not) from the enclosing scope
> are no more on the current stack frame. This is done by copying the
> block to the heap along with all the variables it uses, and if two
> blocks uses/modifies the same __block variable in the declaration
> scope, both blocks will see the same changes, even when copied on the
> heap.

C++ supports [=]{...} syntax which takes copies and lets you use
variables after the originals have gone out of scope.  Is that what
you're looking for?

-- 
Cory Nelson



More information about the cfe-dev mailing list