Avoid GC with closures

Iakh via Digitalmars-d digitalmars-d at puremagic.com
Sat May 28 12:33:52 PDT 2016


On Thursday, 26 May 2016 at 21:10:30 UTC, bpr wrote:
> On Thursday, 26 May 2016 at 18:53:35 UTC, Iakh wrote:
>> Functions with lambdas cannot be @nogc as far as they 
>> allocates closures.
>
> Counterexample:
>
> //  Note that this is NOT a good way to do numerical quadrature!
>
> double integrate(scope double delegate(double x) @nogc f,
>                  double lo, double hi, size_t n) @nogc {
>   double result = 0.0;
>   double dx = (hi - lo) / n;
>   double dx2 = dx * 0.5;
>   for (size_t i = 1; i <= n; i++) {
>     result += f(lo + i * dx2) * dx;
>   }
>   return result;
> }
>
> double integrate(scope double delegate(double, double) @nogc f,
>                             double x0, double x1,
>                             double y0, double y1,
>                             size_t nX, size_t nY) @nogc {
>   return integrate((y) => integrate((x) => f(x,y), x0, x1, nX), 
> y0, y1, nY);
> }
>
> Functions with @nogc downward funarg lambdas (delegates) can be 
> @nogc.
>

Didn't know about "scope". It solves problem partially.

> I can't parse the rest of your post, maybe I misunderstand you.

The problem is that delegates allocates with GC. And proposed
solution it to tell to the compiler what to use instead of GC 
heap.
It is not only about scoped. It is mostly about memory allocated
for closure.


More information about the Digitalmars-d mailing list