3 ms·
What's this about lambdas and GC? Are they reference counted?
by melony 5y ago
What's this about lambdas and GC? Are they reference counted?
- jcelerier 5y agoNot at all. But if you are saving lambdas for callbacks or other async things you'll generally want to add your own layer of reference counting anyways, unless your software architecture is very clear from the beginning.
- tialaramex 5y agoLambda expressions are a place where it's particularly likely that your mental model of what's going on isn't correct, or fails to account for something important in some edge case and so you lose track of who "owns" objects and thus is responsible for cleaning them up and when they need to do so. With GC, this might cause a small unexpected leak of some kind. But in a language like C++ it can be Undefined Behaviour and all bets are off.
- brandmeyer 5y agoThat's part of why the capture list is explicit in C++. Automatic by-reference captures should only be used for lambdas whose scope is strictly lexical (ie, passed down the call stack, aka "downward funargs"). Otherwise stick with by-value captures.
- asveikau 5y agoC++ lambda captures can follow the copy constructor, so that when the lambda is copied, the captures copy too. Or you can capture by reference, which is easier to wander into unsafe situations with. So a lot of times if you want the captures to stay alive but don't want a deep copy, you'll make a std::shared_ptr<> and capture that, which leads to reference counted captures.