首页 > 解决方案 > 在 Lambda 中捕获后移动 std::unique_str

问题描述

在阅读文档时: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

当我们通过udo_something_with(),我们应该使用std::move(u)吗?我的意思是do_something_with(std::move(u))givenu仍然作为 unique_ptr 仅移动,尽管它在 lambda 中捕获。

谢谢您的帮助!

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

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

解决方案


您传递udo_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 中的示例非常简单,同时保留了描述性的函数名称。


推荐阅读