Re:Closures and Objects Are Equivalent (2013)
by magicalhippo on Sunday November 20, 2022 @09:01AM
(#33680939)
In Delphi, closures are implemented pretty much exactly as your second variant. They're implemented using a compiler-generated class.
A difference is that you can't specify capture type, all captured variables are stored as fields in the class, and any outer references (such as x here) are replaced to use the field in the instance:
struct GetxFunctionObject {
int x;
int operator()() { return x; }
};
const auto getx = GetxFunctionObject();
getx.x = 5; // compiler automatically changes "x = 5" to this
getx(); // 5
Modulo any it's-too-early-in-the-morning-to-write-C++ mistakes I made.I can't recall the details if multiple closures captures the same variable, might be the "obvious" solution of a shared data-class instance.
Not in any language I've used. I'm not sure what language you've used but in C++ you would have written:
But that's exactly the same as this: (Something like that anyway; it's been a while since I wrote C++)