四时宝库

程序员的知识宝库

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

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不要有条件对对象实施移动操作。

觉得本文有帮助?请分享给更多人。

更多更新文章,欢迎关注微信公众号【面向对象思考】

面向对象设计,面向对象编程,面向对象思考!

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接