Manually allocate delegate?

Tofu Ninja via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 12 03:39:42 PDT 2015


On Sunday, 12 July 2015 at 10:19:02 UTC, Baz wrote:
> You can copy a delegate in a GC-free chunk but so far i think 
> that the simple fact to get a delegate with "&" will allocate 
> from the GC.
>
> By the way i'd be interested to see the runtime function that 
> creates a delegate.
> i see nothing in druntime.
>
> ---
> import std.stdio, std.c.stdlib, std.c.string;
>
> class Foo {
>     void bar(){writeln("bang");}
> }
>
> void main(string[] args) {
>     auto foo = new Foo;
>     auto dg0 = &foo.bar;
>     auto dg1 = *cast(void delegate()*) malloc(size_t.sizeof * 
> 2);
>     memmove(cast(void*)&dg1, cast(void*)&dg0, size_t.sizeof * 
> 2);
>     dg1();
> }
> ---

That is not manually allocating a delegate context, and & in that 
instance does not even allocate. For delegates to class methods, 
the context is just the "this" pointer of the object, so the 
context in that code is just foo, which you still allocated on 
the gc. The delegate itself (the function pointer and the context 
pointer) is just allocated on the stack.

What I am talking about is the context that implicitly gets 
allocated when you make a delegate to a nested function.

void main(string[] args)
{
	auto d = bar();
	d();
}


auto bar()
{
	int x = 5;
	
	void foo()
	{
		writeln(x);
	}
	
	auto d = &foo; // <-- allocates
	return d;
}




More information about the Digitalmars-d-learn mailing list