c++ - 在 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
当我们通过u
时do_something_with()
,我们应该使用std::move(u)
吗?我的意思是do_something_with(std::move(u))
givenu
仍然作为 unique_ptr 仅移动,尽管它在 lambda 中捕获。
谢谢您的帮助!
注意:我遇到了这个:https ://stackoverflow.com/a/16968463/13097437但它只是引用了我认为上面有问题的例子。
解决方案
您传递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 中的示例非常简单,同时保留了描述性的函数名称。
推荐阅读
- python - 如何在 Python 中找到一个 id 的所有孩子?
- python - Azure python Runbook 在门户中运行失败,但相同的代码在开发框中成功
- python - 如何解决python中的地理定位api错误
- powerbi - 获取当前所选月份的日期值直到前几个月
- html - 绝对 div 内的图标未居中
- ios - 如何检测光标在 iOS 中点击 UITextField 时没有改变?
- pandas - Pandas:使用 chunksize 选项读取 csv 时如何从 csv 文件末尾跳过 n 行
- android - AOSP增量OTA申请失败
- firebase - 在 Flutter 中禁用 Firestore 上的缓存
- playwright - playwright-python - `handleSIGTERM=False` 导致 UnhandledPromiseRejectionWarning 并关闭浏览器