Opportunities for D

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 9 15:16:37 PDT 2014


On Wed, Jul 09, 2014 at 11:33:09PM +0200, Johannes Pfau via Digitalmars-d wrote:
[...]
> For delegates scope can prevent closure heap allocation. For all other
> types it does nothing. Example:
> 
> import std.stdio;
> 
> void testA(void delegate() cb)
> {
>     cb();
> }
> void testB(scope void delegate() cb)
> {
>     cb();
> }
> 
> void main()
> {
>     int a;
>     void callback() {a = 42;}
> //Callback accesses a, testA might store a reference to callback
> //->a might be accessible after this main function returns
> //->can't keep it on the stack. Allocate a on the heap
>     testA(&callback); 
> 
> //Callback accesses a, but testB does not store a reference
> //as it tells us by using scope
> //So as soon as testB returns, there's no reference to a floating
> //around and we can allocate a on the stack.
> //(Of course as long as we call testA in this function, a is always on
> // the heap. but if we only call testB it can be on the stack)
>     testB(&callback);
> }

Unfortunately, it seems that this is not enforced by the compiler at
all. For example:

	int delegate() globDg;
	
	void func(scope int delegate() dg) {
		globDg = dg;	// shouldn't compile, but does
		globDg();
	}
	
	void sub() {
		int x;
		func(() { return ++x; }); // oops
	}
	
	void trashme() {
		import std.stdio;
		writeln(globDg()); // prints garbage
	}
	
	void main() {
		sub();
		trashme();
	}

If 'scope' is commented out, then it works as expected (i.e., x gets
allocated on the heap).

	https://issues.dlang.org/show_bug.cgi?id=13085


T

-- 
Dogs have owners ... cats have staff. -- Krista Casada


More information about the Digitalmars-d mailing list