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?
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.
https://dlang.org/spec/attribute.html#nogc
... means that that function does not allocate memory on the GC heap, either directly such as with NewExpression or indirectly through functions it may call, or through language features such as array concatenation and dynamic closures.
It doesn't tell anything about GC state after function execution or overall memory usage increase. Only thing that matters is that function itself is guaranteed to never call any GC allocation functions, i.e. you could reliably build and run such function with a custom runtime that doesn't have GC implementation linked in at all.
Another important point is that @nogc can't be affected by optimizations because same valid code must keep compiling with different optimization levels and different compilers. Any such optimizations would need to become mandatory in language specification before @nogc can take use of it.
With all that in mind your described function could get valid @nogc annotation only when both following conditions apply:
I see it as extremely unlikely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With