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() .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.
templateusing 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.
templateusing capture_impl = ...; auto lambda = capture(std::move(val), [](auto&& v) { return std::forward (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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3