4 ms·
Generalised capture In C++11, lambdas can only capture existing objects in their scope: int z = 42; auto myLambda = [z](int x){ std::cout << x << '
by 1024core 5y ago
Generalised capture
In C++11, lambdas can only capture existing objects in their scope:
int z = 42;
auto myLambda = [z](int x){ std::cout << x << '-' << z + 2 << '\n'; };
...
But with the powerful generalised lambda capture, we can initialise captured values with about anything.
int z = 42;
auto myLambda = [y = z + 2](int x){ std::cout << x << '-' << y << '\n'; };
Am I the only one who doesn't see much of a difference here?
- ynik 5y agoGeneralized capture is primarily useful for move semantics: std::function<int()> make_func(std::unique_ptr<int> ptr) { return [p = std::move(ptr)]() { return *p; } } Without generalized capture syntax, there's no good way to transfer ownership into the closure (a regular `[ptr]` capture would attempt to make a copy, and a by-ref `[&ptr]` capture would lead to a use-after-free).
- deleted 5y ago[deleted]