4 ms·
I’m not sure about C++ in particular, but in general a lambda can capture a lexically scoped value and expects to still be able to access it even after the stac
by User23 5y ago
I’m not sure about C++ in particular, but in general a lambda can capture a lexically scoped value and expects to still be able to access it even after the stack frame it got allocated in is popped. GC is the most straightforward way to keep that from leaking.
On a tangential note, the amount of Greenspunning C++ has done over the last two decades is truly impressive. There sure is a lot of syntactic noise though.
- NL807 5y agoC++ lambdas are effectively callable objects, basically an anonymous class with an implicit operator(...) built in. They can capture other objects by value, which means those objects' lifetime is tied to the lambda object itself. When the lambda object goes out of scope, the captured objects' destructor will be called. There will be no leaks. Of course, if you capture by reference, this does not apply.
- betterunix2 5y ago"Capture by value" is meaningless since an object could itself contain references. Combined with the fact that lambdas can have side effects (there is no way to avoid this in C++) it is actually possible for a lambda to wind up owning itself. Imagine a class that has a pointer to a function object as a member, whose type is compatible with a lambda that captured an object of that class. Now that lambda might call a setter for that class member, using one of its own arguments as the argument to the setter. Apply the lambda to itself, and now the lambda owns itself via its ownership of the captured object. I have no idea what happens in this situation, but it is not at all impossible to wind up with something like this in a complicated and large codebase.
- nwallin 5y agoThat's why C++ requires you to explicitly list the stuff you want to capture, and whether you want to capture it by value or by reference, and the least-keystrokes way to capture is to capture by value. Capturing a reference to something on the stack is an option which requires extra work. C++ is predominantly a language that's oriented around value types instead of reference types. If you have a reference it's because you've taken extra steps to ensure the thing you have is a reference. As opposed to Java, Python, C#, Javascript, PHP etc where most everything is a pointer to somewhere. Suggesting that C++ adopt GC to solve the problem of capturing references on the stack in lambdas is akin to suggesting that the Netherlands solve its biking/transportation problems by subsidizing cars and gasoline. It's not even wrong.