Capture List By Value By Reference [this] [a,b] [=] [&a,&b] [&] Prefer Explicit Captures Over Default Captures
class A { public: int x; A(): x(10) {} std::function<bool()> getLambda() { return [=] (){ return x+2; }; } }; int main() { A* a = new A(); auto lambda = a->getLambda(); delete a; lambda(); } This is implicitly this->x. The this parameter is what gets captured, not x.
class A { public: int x; A(): x(10) {} std::function<bool()> getLambda() { return [copy=x] (){ return copy+2; }; } }; int main() { A* a = new A(); auto lambda = a->getLambda(); delete a; lambda(); } C++14 gives us init captures, where we can initialize the variables we capture (useful for any non-local captures)
Why? Dependency Injection Pass a function to inject a dependency Functional Programming Styles Mapping and Filtering just got a whole lot easier Algorithm Library auto isSpecial = [](MacAddress& mac){ return MacAddress::ItuAddress == mac; }; any_of(macs.begin(), macs.end(), isSpecial ); count_if(macs.begin(), macs.end(), isSpecial ); replace_if(macs.begin(), macs.end(), isSpecial , MacAddress::BlankMacAddress); sort(ips.begin(), ips.end(), [](IpAddressV4& ip1, IpAddressV4& ip2) { return ip1.getNetworkByteOrder() < ip2.getNetworkByteOrder()); });
[] () {} Capture List Parameters Function Body ();