Search code examples
garbage-collectiondpurely-functional

Does a pure and nothrow function which does not pass out memory automatically collect garbage?


Assume you have a function in D that is pure and nothrow and by its return type and argument types cannot pass out any newly allocated memory. Can I add the @nogc attribute to this function then? If not, are there chances that this will be possible in the future?

My point here is the following: Since the function does not have any visible side effects, all memory that was allocated on the way can be freed deterministically at function exit. Hence, the GC is not really required, since the mark and sweep step can be avoided. Or can it not?


Solution

  • You can always try adding @nogc and compiling. A pure function may still allocate internal buffers, even if it doesn't return any of them, so the question of garbage collection is on a different axis than purity.

    If it passes compilation with @nogc, it will not allocate (and thus not collect, the D GC will only ever collect when you ask it to allocate) regardless of purity.