2 ms·
You can do manual closure management. int f() { int x = 42; return dupclosure(^(){return x+10}}; } int g() { int (^
by ori_b 15y ago
You can do manual closure management.
int f() {
int x = 42;
return dupclosure(^(){return x+10}};
}
int g()
{
int (^fn)();
fn = f();
fn();
freeclosure(fn);
}
It's not quite as pretty, but it's workable, and in line with a C-family language's semantics.
- seabee 15y agoHowever it does require severe adjustments to the lifetime rules for automatic variables, and you have to be mindful of e.g. custom allocators.
- ori_b 15y agoCustom allocators are relatively easy handle with an API something like: void* closureheap(void (^)()) size_t closuresize(void(^)()) Or, well, anything else that allows you to separate the step of allocating memory from it's initialization. (There are probably more representation-independent APIs that would be better, but this was just off the top of my head) And, yes, mutable captured variables will not be shared across multiple duplications. Somewhat unconventional, but given the mental model of copying closures, I don't think it's a surprising behavior.