【问题标题】:Move std::unique_str after its captured in Lambda在 Lambda 中捕获后移动 std::unique_str
【发布时间】:2020-12-18 02:09:58
【问题描述】:

阅读文档时:https://isocpp.org/wiki/faq/cpp14-language#lambda-captures,

    auto u = make_unique<some_type>( some, parameters );  // a unique_ptr is move-only
    go.run( [ u=move(u) ] { do_something_with( u ); } ); // move the unique_ptr into the lambda

当我们在do_something_with() 中传递u 时,我们应该使用std::move(u) 吗?我的意思是 do_something_with(std::move(u)) 给定 u 尽管它在 lambda 中捕获,但它仍然作为 unique_ptr 仅移动。

感谢您的帮助!

注意:我遇到了这个:https://stackoverflow.com/a/16968463/13097437,但它只是引用了我认为上面有问题的示例。

【问题讨论】:

    标签: c++ lambda c++14 unique-ptr


    【解决方案1】:

    如何将 u 传递给 do_something_with 与是否使用 lambda 无关。如果do_something_with 被声明为

    void do_something_with(std::unique_ptr<some_class> u)
    

    也就是说,它通过值获取其参数,那么是的,您需要将调用者的指针移动到函数调用中。另一方面,如果do_something_with 被声明为

    void do_something_with(std::unique_ptr<some_class> & u)
    

    也就是说,它通过引用获取它的参数,那么不,试图移动调用者的指针是没有意义的。

    鉴于这两种可能性都是有效的,该示例与产生更简单代码的那个一起使用。不要过多解读。

    就个人而言,我认为像do_something_with(*u)(传递指向对象)这样的调用比直接传递指针更有可能,但当然一种尺寸并不适合所有人。 C++ FAQ 中的示例非常简单,同时保留了描述性函数名称。

    【讨论】:

      【解决方案2】:
      auto u = make_unique<some_type>( some, parameters );  // a unique_ptr is move-only
      go.run( [ u=move(u) ] { do_something_with( u ); } ); // move the unique_ptr into the lambda
      

      我愿意

      auto u = make_unique<some_type>( some, parameters );  // a unique_ptr is move-only
      go.run( [ u=move(u) ]()mutable { do_something_with( std::move(u) ); } ); // move the unique_ptr into the lambda
      

      auto u = make_unique<some_type>( some, parameters );  // a unique_ptr is move-only
      go.run( [ u=move(u) ] { do_something_with( u.get() ); } );
      

      取决于我是否要转让所有权。

      但这只是质量。如果 do something with 通过 const 引用获取其参数,则代码按原样编译。

      但是,我通常建议不要使用 const 引用唯一 ptr 参数。这就像通过 const 引用传递一个向量;您不必要地用实现细节(用于存储指针的确切类或连续缓冲区)限制参数的类型。

      【讨论】:

        猜你喜欢
        • 2012-05-04
        • 2012-01-28
        • 1970-01-01
        • 2021-04-12
        • 2018-03-15
        相关资源
        最近更新 更多