Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I always thought that if you wanted variables to be able to escape the function they were defined in you have to allocate them on the heap and then you need some kind of garbage collection.


If you want them only to "escape" down the stack then it's not necessary. If you want them to escape up the stack then of course you can't have them capture a pointer to the stack variable, because that will no longer exist once the current function returns. However if you capture all variables by value and make the lambda an unique type containing all the captured variables then you can return it up the stack. Of course the downside of this is that each lambda gets its own different type, but you can add ways to convert them to a common type at the cost of having to then deal with the allocation issue at that point.


You can also have some kind of heapify/free, with undefined behavior if you get it wrong.

I think the C standards committee needs to figure out memory safety before adding any new features that are likely to interact with it.


So you're saying the runtime mallocs the pointer to the closure and it's your responsibility to free it when you don't need it anymore?


Kinda. Here's an example:

     void
     mkclosure(int x)
     {
         int x;
         void fn(void){ return x + 1; }
         return fnheapify(fn);
     }

     void
     useclosure(void)
     {
         void (^fn)(void) = mkclosure(42);
         fn();
         fnfree(fn);
     }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: