"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > C ++ Lambda의 모바일 캡처 구현 팁

C ++ Lambda의 모바일 캡처 구현 팁

2025-04-12에 게시되었습니다
검색:494

How to Implement Move Capture in C   Lambdas?

Move Capture in Lambdas

Question:

How do we implement move capture, also known as rvalue references, in C 11 lambdas? 예를 들어 :

std::unique_ptr myPointer(new int);

std::function example = [std::move(myPointer)] {
   *myPointer = 4;
};

네임 스페이스 std를 사용합니다. auto u = make_unique (일부, 매개 변수); go.run ([u = move (u)] {do_something_with (u);});

헬퍼 함수 Make_rref는 이동 캡처를 용이하게 할 수 있습니다. 구현은 다음과 같습니다. #포함 #include #include 템플릿 struct rref_impl { rref_impl () = 삭제; rref_impl (t && x) : x {std :: move (x)} {} rref_impl (rref_impl 및 기타) : x {std :: move (Other.x)}, iscopied {true} { assert (기타 .iscopied == 거짓); } rref_impl (rref_impl && other) : x {std :: move (기타 .x)}, iscopied {std :: move (eloge.iscopied)} { } RREF_IMPL & OPERATOR = (RREF_IMPL 기타) = 삭제; T & Operator && () { 반환 std :: move (x); } 사적인: t x; bool iscopied = false; }; 템플릿 rref_impl make_rref (t && x) { rref_impl {std :: move (x)}를 반환합니다. }

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)};
}

캡처는 다음과 같이 구현됩니다 템플릿 클래스 capture_impl { t x; F F; 공공의: capture_impl (t && x, f && f) : x {std :: promper (x)}, f {std :: forward (f)} {} 템플릿 auto operator () (ts && ... args) -> decltype (f (x, std :: forward (args) ...))) { return f (x, std :: forward (args) ...); } 템플릿 auto operator () (ts && ... args) const -> decltype (f (x, std :: forward (args) ...))) { return f (x, std :: forward (args) ...); } }; 템플릿 capture_impl capture (t && x, f && f) { 캡처 캡처 _impl ( std :: promper (x), std :: promper (f)); }

int main() {
    std::unique_ptr p{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