Apple Blocks added to C++?

Mattias Holm mattias.holm at openorbit.REMOVE.THIS.org
Wed Sep 2 09:08:09 PDT 2009


Leandro Lucarella wrote:

> GCC support them as an extension to C for ages too.
> 

True for nested functions but nested functions are not blocks.

typedef void (*foo_t)(void);

foo_t getSomeFunc()
{
	int x = 4;
	void bar(void) {
	    printf("%d\n", x);
	}
	return bar;
}

foo_t func = getSomeFunc();
func(); // Undefined, nested functions cannot be returned and in any 
case, no variable capturing will happen, so the variable x is undefined 
when func is called above getSomeFunc.


On the contrary, the following would work very well with blocks:

typedef void (^foo_t)(void);

foo_t getSomeBlock()
{
	int x = 4;
	void ^bar(void) {
	    printf("%d\n", x);
	}
	return Block_copy(bar);
}

foo_t blk = getSomeBlock();
blk(); // Will happily print 4
Block_release(blk); // free up memory of block


Though, they could probably make some hacks to gcc to add the copying 
and variable capturing to nested functions. Such hacks would most likely 
break a lot of code as the ABIs would have to be changed.

This means that blocks are very suitable for enqueuing in something 
using the thread pool pattern, this is what GCD does and in my humble 
opinion GCD is a very very nice concurrency model for C. The main issues 
now being that GCD is seriously in need of standardisation through 
POSIX, and the C language.

I suppose that blocks will not be added to C officially for quite some 
time, and therefore neither in POSIX. I think they should work out a 
version of C that includes that in the standard, like they have done for 
embedded applications, i.e. a set of extensions to the core language.


/ Matt



More information about the Digitalmars-d mailing list