首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则编译边学-F.18 使用X&&传递“将会发生数据移动”的参数并实施数据移动

C++核心准则编译边学-F.18 使用X&&传递“将会发生数据移动”的参数并实施数据移动

作者头像
面向对象思考
发布2020-03-25 15:22:32
4880
发布2020-03-25 15:22:32
举报

F.18: For "will-move-from" parameters, pass by X&& and std::move the parameter(使用X&&传递“将会发生数据移动”的参数并实施数据移动)

Reason(原因)

It's efficient and eliminates bugs at the call site: X&& binds to rvalues, which requires an explicit std::move at the call site if passing an lvalue.

对于调用者可以提供高效和排除bug的可能性:X&&绑定一个右值,当调用者传递左值是需要使用清楚的std::move操作。

Example(示例)
void sink(vector<int>&& v) {   // sink takes ownership of whatever the argument owned
    // usually there might be const accesses of v here
    store_somewhere(std::move(v));
    // usually no more use of v here; it is moved-from
}

Note that the std::move(v) makes it possible for store_somewhere() to leave v in a moved-from state.That could be dangerous.

注意:std::move造成store_somewhere执行后,v变成移动后状态。这可能很危险。

译者注:危险在于移动后对象处于无效状态,一旦被使用则任何事情都可能发生。

Exception(例外)

Unique owner types that are move-only and cheap-to-move, such as unique_ptr, can also be passed by value which is simpler to write and achieves the same effect. Passing by value does generate one extra (cheap) move operation, but prefer simplicity and clarity first.

For example:

独占所有权类型只用于移动而且移动的成本很低,例如unique_ptr,可以使用容易编写且(和移动操作)效果相同的传值方式。传值确实会生成一个额外的(低成本的)移动操作,但是这里优先选择简单和清晰。

template <class T>
void sink(std::unique_ptr<T> p) {
    // use p ... possibly std::move(p) onward somewhere else
}   // p gets destroyed

Enforcement(实施建议)
  • Flag all X&& parameters (where X is not a template type parameter name) where the function body uses them without std::move. 提示所有函数体中没有对其使用std::move操作的X&&参数(这里X不是模板类型参数名)。
  • Flag access to moved-from objects. 提示对移动后对象的访问。
  • Don't conditionally move from objects 不要有条件对对象实施移动操作。
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-11-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.18: For "will-move-from" parameters, pass by X&& and std::move the parameter(使用X&&传递“将会发生数据移动”的参数并实施数据移动)
    • Reason(原因)
      • Example(示例)
        • Exception(例外)
          • Enforcement(实施建议)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档