4 ms·
I love lambdas, but a lot of commenters are throwing around the word "closure" here, and c++ lambdas are definitely not closures. You can capture outside variab
by hellofunk 10y ago
I love lambdas, but a lot of commenters are throwing around the word "closure" here, and c++ lambdas are definitely not closures. You can capture outside variables by value or by reference, but that value can expire before the lambda runs if the reference no longer exists; in which case, you are in trouble. Unlike a true closure (as in lisp or other languages), where the closed-over value stays around.
If we talk only about c++ capture lists by value (i.e. [=]), then you could make a case for a more appropriate use of the word "closure" but since many lambdas do more than this, I think the distinction is necessary.
However, even in by-value captures, if you are capturing a pointer by value, the issue remains. So, really it is not a good idea to think of lambdas as closures in the functional sense typically used in other languages.
- leni536 10y agoI'm not familiar with closures from other languages. What about capturing a shared_ptr by value?
- thrownaway2424 10y agoThe thing to keep in mind is that copying a shared_ptr isn't cheap at all. It's a class with a pointer and atomic reference count inside and the atomic inc/dec takes many cycles.
- leni536 10y agoHow does this compare to the cost of a closure in other languages? Yeah atomic reference counts are not cheap, but basically that's the point of a shared_ptr.
- thrownaway2424 10y agoI'm not sure. I don't program in C++ because I want it to have performance comparable to other languages.
- csl 10y agoI find that pointlessly pedantic. By the same measure, languages that don't offer bignums don't offer integers. Even Lisps need to implement closures in one way or another, and you may be surprised to see how they actually do it.
- moonshinefe 10y agoI think you miss the point, the OP was mentioning the property that in most languages, closures whose outer variables they are bringing into scope stay in scope (even if the outer function ends). In C++ they expire (is what I got from his comment, anyway).
- gpderetta 10y agoClosed-by-value variables (I.e. the default) in C++ don't expire. Referenced or pointed-to object might, but this is completely consistent with the rest of the language. Remember that C++ is a by value language. Pointers are explicit, fist class and distinct from the pointed to object. References are werid, though.
- makecheck 10y agoYou would have to combine copying and reference management, e.g. "[=]" and std::shared_ptr<>. It definitely requires the programmer to pay more attention though, compared to other languages/constructs.