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

I figure closures would be hard to do in a programmer-friendly way without GC.


The C++ closure library we use internally at Google has you specify whether the callback is permanent or not. If it isn't permanent, its deleted right after executing. It is a little painful maintaining the memory of your arguments, but people have generally converged to packing them all into a heap allocated struct and deleting when appropriate.


C++0x managed to add closures without adding GC. The only issue is that if you want to the closure to outlive the current stack frame you have to capture by value ([=] rather than [&]) or use a shared_ptr (which is then copied by value).


If you implement closures as thunks, you can just free them when done, no need for GC.

    closure int foo(int x) {return x + y;}
    int(*foo_p)(int) = malloc(sizeof(foo));
    memcpy(foo_p,&foo,sizeof(foo));
    return foo_p;
So, you can add working closures in one keyword (and possibly a special case for function pointer decay).


smart pointers would also do it.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

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

Search: