Move Capture in Lambdas
Question:
How do we implement move capture, also known as rvalue references, in C 11 lambdas? 예를 들어 :
std::unique_ptrmyPointer(new int); std::function example = [std::move(myPointer)] { *myPointer = 4; };
네임 스페이스 std를 사용합니다.
auto u = make_unique
헬퍼 함수 Make_rref는 이동 캡처를 용이하게 할 수 있습니다. 구현은 다음과 같습니다. #포함
make_rref에 대한 테스트 케이스 :
using namespace std; auto u = make_unique(some, parameters); go.run([u = move(u)] { do_something_with(u); });
C 11
go.run([u = move(u)] mutable { do_something_with(std::move(u)); });
#include#include #include template struct rref_impl { rref_impl() = delete; rref_impl(T&& x) : x{std::move(x)} {} rref_impl(rref_impl& other) : x{std::move(other.x)}, isCopied{true} { assert(other.isCopied == false); } rref_impl(rref_impl&& other) : x{std::move(other.x)}, isCopied{std::move(other.isCopied)} { } rref_impl& operator=(rref_impl other) = delete; T& operator&&() { return std::move(x); } private: T x; bool isCopied = false; }; template rref_impl make_rref(T&& x) { return rref_impl {std::move(x)}; }
캡처는 다음과 같이 구현됩니다
템플릿
int main() { std::unique_ptrp{new int(0)}; auto rref = make_rref(std::move(p)); auto lambda = [rref]() mutable -> std::unique_ptr { return rref.move(); }; assert(lambda()); assert(!lambda()); }
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3