Nested delegates and closure allocations

Anonymouse zorael at gmail.com
Tue Jan 16 10:56:58 UTC 2024


I'm increasingly using nested delegates to partition code.

```d
void foo(Thing thing)
{
     void sendThing(const string where, int i)
     {
         send(thing, where, i);
     }

     sendThing("bar", 42);
}
```

...where the nested `sendThing` sometimes returns something, 
sometimes doesn't. `Thing` may be a class or a value type, 
`thing` may be a parameter to the parent function, may be a 
variable previously declared in the parent function, may be 
mutable or immutable, may be modified inside `sendThing`; any 
combination of things. If `sendThing` doesn't need to access the 
scope of `foo` I mark it `static` to enforce that, but mostly it 
does.

 From the spec:

> ### `19.19.2` Delegates & Closures
>
> 3. Those referenced stack variables that make up the closure 
> are allocated on the GC heap, unless:
>
> * The closure is passed to a scope parameter.
> * The closure is an initializer for a scope variable.
> * The closure is assigned to a scope variable.

I'm generally not storing the delegates or passing them around as 
values, so I don't think the thing about scope variables and 
parameters *directly* applies.

Am I safe as long as I don't do something like, pass `&sendThing` 
as an argument to `std.concurrency.receive`?


More information about the Digitalmars-d-learn mailing list