Closures and Memory Management

Steven Wawryk stevenw at acres.com.au
Tue Apr 26 19:27:28 PDT 2011


The requirement to use manual memory management and *not* have a garbage 
collector is the rule rather than the exception in the domains of 
embedded and OS development.

You'll often hear in these groups that you "can turn the GC off", but 
that's not actually true.  The GC *can* be disabled (intended to be 
temporary) to prevent collection cycles during critical pieces of code, 
but to not use it at all is not a serious option.  The GC is used to 
allocate memory extensively in language features and in Phobos, and to 
avoid using those leaves a severely lobotomised subset.  Language 
features that allocate through the GC are documented at:

http://www.digitalmars.com/d/2.0/garbage.html

but there is no documentation that I know of that lists the parts of 
Phobos that you can't use without the GC.

Given all the nice things about D I would love to have a RAII option as 
a first class option that lets you plug in the memory manager you choose 
but I don't think it's going to happen.  I don't remember where I read 
it, but I remember reading somewhere that this won't happen because to 
write libraries that can be used with either GC or RAII requires that 
they be written for RAII, ie with explicit delete's in destructors etc, 
and that's been rejected as a possibility for the language and Phobos.

Unfortunately, I would have to say that for applications and domains in 
which you require no garbage collection then D is not a serious option.


On 21/04/11 08:37, Andrew Wiley wrote:
> I'm working on a project that looks like it'll need manual memory
> management (the end goal is to get it running on ARM using GDC, where
> the GC doesn't seem to behave (that goal might be unrealistic, but I can
> hope)), and I'm trying to figure out how to deal with closures. My
> understanding is that a closure is a function pointer and the enclosing
> scope, whether that scope is variables that are copied into the closure
> or a class instance to use as "this." Is this correct?
>
> Assuming that's correct, this would involve a memory allocation, right?
> ----------
> class Test {
> void doStuff() {}
> }
>
> void doSomethingElse(void delegate() thing) {
> thing();
> }
>
> void main() {
> auto test = new Test();
> doSomethingElse(&test.doStuff);
> }
> ----------
>
> My understanding is that as soon as I run "&test.doStuff" a closure is
> generated. Is this correct? Would it then be valid, in doSomethingElse,
> to run "GC.free(thing)" ?
>
> Any insight would be appreciated.



More information about the Digitalmars-d mailing list