In C 11, capturing variables in lambdas is generally done by reference. This reference remains alive as long as the lambda exists, which can sometimes lead to unintended behavior if the captured variable is moved out.
In C 14, generalized lambda capture was introduced, allowing for move capture. This enables convenient manipulation of move-only types, such as unique pointers.
std::make_unique<int>() .then([u = std::move(u)] { do_something_with(u); });
Prior to C 14, move capture can be emulated using helper functions:
This approach creates a wrapper class, rref_impl, that encapsulates the value and manages its lifetime.
template <typename T> using rref_impl = ...; auto rref = make_rref(std::move(val)); [rref]() mutable { std::move(rref.get()); };
However, capturing rref in a lambda allows it to be copied, potentially leading to runtime errors.
This method uses a function that takes the captured value by reference and returns a lambda that calls the function with the captured value as an argument.
template <typename T, typename F> using capture_impl = ...; auto lambda = capture(std::move(val), [](auto&& v) { return std::forward<decltype(v)>(v); });
This prevents copying the lambda and ensures that the captured value is moved into the lambda's scope.
Remember, these workarounds are not as elegant as the generalized lambda capture in C 14, but they provide a way to emulate move capture in earlier versions of the language.
The above is the detailed content of How Can I Achieve Move Capture in C Lambdas, Especially in C 11?. For more information, please follow other related articles on the PHP Chinese website!