3 ms·
I think you have a mistake in what you wrote, but please correct me if I am wrong. C++11 lambdas which capture free variables by reference can not be returned
by jjtheblunt 11y ago
I think you have a mistake in what you wrote, but please correct me if I am wrong.
C++11 lambdas which capture free variables by reference can not be returned from a function in which the free variables occur, and be expected to work, because the function's variable (a free variable to the lambda) may no longer refer to memory allocated for use as the variable.
That's not true for Scheme. Scheme's underlying implementation of lambda and function call means that true closures are created: if a lambda refers to a variable which is not local to (or a parameter to) the lambda, then that free variable belongs to an environment, whose lifetime isn't delimited by popping a stack and returns, and is therefore still live as long as some closure (or stack activation frame) refers to it. Return of a lambda with free variables will work in Scheme, and can fail in C++11.
- pmelendez 11y agoYou are correct in the sense that Scheme and C++ handle non-local variables and non-parameters differently (In C++ you can also capture variables by value, but I don't think there is a proper free variable capture mechanism at all). However, that's not what I meant when I wrote that. I was referring this quote: "being able to concisely define executable "objects" (closures), inline if necessary, is very useful" The fact that you can define inline executable objects is indeed very useful, and C++ does exactly that: an inline mangled class instantiated bounded to one variable. It would be cool to have free variable in C++ in the same way that Scheme handles it, but I don't think the language would get there anytime soon (Gee, it is still cumbersome to have recursive lambdas).