| ▲ | Lambdas, Nested Functions, and Blocks (2021)(thephd.dev) |
| 44 points by zaikunzhang 6 days ago | 9 comments |
| |
|
| ▲ | PaulHoule 3 days ago | parent | next [-] |
| 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. |
| |
| ▲ | SkiFire13 3 days ago | parent | next [-] | | 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. | |
| ▲ | ori_b 3 days ago | parent | prev [-] | | 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. | | |
| ▲ | PaulHoule 3 days ago | parent [-] | | 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? | | |
| ▲ | ori_b 3 days ago | parent [-] | | 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);
}
|
|
|
|
|
| ▲ | remexre 3 days ago | parent | prev | next [-] |
| Are there any implementations of this lambdas proposal on top of any production-quality compilers? Or are there some updates on how this is doing in committee? |
| |
|
| ▲ | mwkaufma 3 days ago | parent | prev [-] |
| "Unfortunately, many compiler authors would absolutely give our recommended advice a gigantic middle finger." Simmer down, now. |