Idea for avoiding GC for lambdas

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jun 22 16:13:06 UTC 2021


On Tue, Jun 22, 2021 at 11:05:18AM -0400, Steven Schveighoffer via Digitalmars-d wrote:
> On 6/21/21 6:19 PM, Elronnd wrote:
[...]
> > Your proposal is essentially a value delegate; the __context stuff
> > makes that explicit, but it's not actually fundamentally different
> > from the current scheme, it's just that the context becomes a value
> > type rather than a reference type.
> 
> Right, I honestly don't know how the context is passed for an alias
> parameter. The compiler must pass some sort of context pointer to the
> calling function, which then gets stored somehow. But it's all hidden.
> If it's hidden, it might as well be as big as needed.

AFAIK, delegates are essentially just:

	struct __dg {
		void* context;
		RetType function(void* context, Args...) func;
	}

An alias parameter, being a template parameter, simply causes the
aliased function to get template-expanded in the body of the delegate.
Any context it carries must be shared with the delegate's context, which
is the source of the recent issue with multi-context template functions
that resulted in the compiler change getting reverted.

The context must be stored *somewhere*, usually on the GC heap, which is
why delegates depend on the GC. Except for scope delegates where it's
guaranteed that the parent scope won't go out of scope before the
delegate does, so the context pointer can just point to the stack where
the parent's scope is stored.

Unless I'm missing something obvious, I don't think value delegates
would work well with D, because it's pretty important for delegates with
the same parameter and return types to be interchangeable. I.e., two
delegates with external type `int delegate(string)` must have the same
fixed size and memory layout, regardless of the size of the context of
one delegate vs. the other, otherwise you have a pretty serious problem
at the language level.


T

-- 
Everybody talks about it, but nobody does anything about it!  -- Mark Twain


More information about the Digitalmars-d mailing list