代码之家  ›  专栏  ›  技术社区  ›  John

复制捕获移动对象的lambda

  •  0
  • John  · 技术社区  · 4 年前

    为什么会这样 code snippet 不编译?

    #include <functional>
    #include <iostream>
    #include <memory>
    
    int main()
    {
        std::unique_ptr<int> uniq_ptr(new int{6});
        auto foo_a = [&uniq_ptr]{std::cout << *uniq_ptr << std::endl;};
        std::bind(foo_a)(); //works
        foo_a();            //works
    
        auto foo_b = [up = std::move(uniq_ptr)]()mutable{*up = 5; std::cout << *up << std::endl;};
        foo_b();           //works;
    
    #ifdef CHOOSE_1
        auto foo_b1 = foo_b; //Surprised!  I think `up` could be copied.But the compiler complains: Error: use of deleted function 'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'
    #else
        std::bind(foo_b);    //Same error!
    #endif
    }
    

    对于 auto foo_b = [up = std::move(uniq_ptr)]()mutable{//...} 我想 foo_b 可以复制自 up 一个右值,它可以被move构造函数复制。

    1 回复  |  直到 4 年前
        1
  •  1
  •   康桓瑋    4 年前

    [up = std::move(uniq_ptr)] 只是移动 uniq_ptr 到lambda的成员变量。

    std::bind 将在内部构建 foo_b 自从 富比 包含一个 unique_ptr 这是不可复制的, 富比 它本身是不可复制的。

    你该走了 富比 进入 绑定 :

    std::bind(std::move(foo_b));
    

    还是搬家 富比 进入 foo_b1

    auto foo_b1 = std::move(foo_b);