Hacker News new | past | comments | ask | show | jobs | submit login

Yeah, any time you have a nested function you raise the question of "what can this close over?" Sometimes the answer is "nothing", and that's not a closure... but it's still an answer to the question so it makes some sense to talk about it in the same breath.



Lambdas are just functions with different syntax. Closures imply keeping some state around, and may require that some variables from outer scopes live longer than they otherwise would. (That's what they're usually used for in Javascript, where you want state kept around for a reply event.)

Closures are easy to implement in garbage-collected languages, but get complicated in non-garbage collected languages. When an inner function normally references variables in an outer scope, they're just references to the stack. But if there's a closure that can outlive the outer scope, those variables have to be saved somewhere.

With C++11 closures, you have to specify what you want to keep around and how you want it kept.[1] Internally, C++11 creates an object to store the variables you want to keep around. This can potentially create lifetime problems, because you can save a reference to a variable, then keep the closure object around longer than the variable being referenced. This creates a dangling pointer. Rust has lifetime checking to catch such errors, but C++11 does not. See this Stack Overflow discussion of how not to shoot yourself in the foot with C++11 closure lifetime undefined behavior.[2]

That's why it's useful to realize that closures and lambdas are not the same thing. Lambdas are simple. Closures are complicated.

[1] http://www.cprogramming.com/c++11/c++11-lambda-closures.html [2] http://stackoverflow.com/questions/27775233/lambdas-and-capt...


I certainly don't mean that there aren't contexts where distinguishing the two is vital to understanding. I just mean there are context where you'll need to talk about both, and I think that's part of the reason they sometimes get conflated.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

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

Search: