GC for pure functions -- implementation ideas

Timon Gehr timon.gehr at gmx.ch
Sat Apr 16 13:49:46 PDT 2011


> Yeah, I never formalized it at all, but that's roughly what TempAlloc
> accomplishes.  My other concern is, what happens in the case of the
> following code:

> uint nonLeaky() pure {
>      foreach(i; 0..42) {
>           auto arr = new uint[666];
>           // do stuff
>      }
>
>      return 8675309;
> }
>
> In this case the arr instance from every loop iteration is retained
> until nonLeaky() returns, whether it's referenced or not.  Granted, this
> is a silly example, but I imagine there are cases where stuff like this
> happens in practice.

It should be trivial to just deallocate when arr goes out of scope.

This would be more complicated to resolve, as the analogy to stack allocation
vanishes:

uint nonLeaky() pure {
     uint[] arr1 = new uint[666];
     uint[] arr2 = new uint[666];
     foreach(i; 0..42) {
          arr1 = new uint[66*i];
          // do stuff
     }

     return 8675309;
}

The problem is, that inside a non-leaky pure function the general case for dynamic
allocations might be just as complicated as in other parts of the program.
However, the problem does only exist when the pure function deletes/overrides its
own references. Those are the only ones it is allowed to modify. Therefore, the
compiler could just use the GC heap whenever a reference is assigned twice or more
times inside a non-leaky pure function? I think it might be a better option than
letting the pure heap fill up with garbage.


More information about the Digitalmars-d mailing list