Home >Backend Development >C++ >How Can I Achieve Move Capture in C 11 Lambdas?
C 14 introduces generalized lambda capture, which allows for move capture. This feature enables code like:
using namespace std; auto u = make_unique<some_type>(some, parameters); go.run([u = move(u)] { do_something_with(u); });
In C 11, move capture can be emulated using a helper function make_rref:
#include <cassert> #include <memory> #include <utility> template <typename T> struct rref_impl { // ... (implementation omitted for brevity) }; template<typename T> rref_impl<T> make_rref( T && x ) { return rref_impl<T>{ std::move(x) }; }
Example usage:
std::unique_ptr<int> p{new int(0)}; auto rref = make_rref(std::move(p)); auto lambda = [rref]() mutable -> std::unique_ptr<int> { return rref.move(); }; assert(lambda()); assert(!lambda());
Generalized lambda capture can also be emulated using a capture function:
#include <utility> template <typename T, typename F> class capture_impl { // ... (implementation omitted for brevity) }; template <typename T, typename F> capture_impl<T,F> capture( T && x, F && f ) { // ... (implementation omitted for brevity) }
Example usage:
std::unique_ptr<int> p{new int(0)}; auto lambda = capture(std::move(p), [](std::unique_ptr<int> &p) { return std::move(p); }); assert(lambda()); assert(!lambda());
The above is the detailed content of How Can I Achieve Move Capture in C 11 Lambdas?. For more information, please follow other related articles on the PHP Chinese website!