D is our last hope

Walter Bright newshound2 at digitalmars.com
Tue Dec 19 20:30:05 UTC 2023


On 12/7/2023 11:01 AM, GrimMaple wrote:
> Delegates is just one of the things where `@nogc` issues 
> are apparent. If you want to have a `@nogc` control in a UI framework and have 
> callbacks/events in it, you are going to force the user of that control to use 
> `@nogc` code.

A delegate will use the GC if both these conditions apply:

1. it references variables in the function it is enclosed by

2. the delegate escapes the context of that function, i.e. it outlives the 
lifetime of that function, so its stack frame no longer exists. In that case, 
the compiler will allocate that function's stack frame using the GC.

To avoid this, do one of:

1. capture the values from the enclosed variables, rather than simply referring 
to them

2. don't use the delegate in such a way that it outlives the function it is 
nested inside


More information about the Digitalmars-d mailing list