温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++使用X&&传递会发生什么

发布时间:2021-11-26 14:28:55 来源:亿速云 阅读:123 作者:iii 栏目:大数据

这篇文章主要介绍“C++使用X&&传递会发生什么”,在日常操作中,相信很多人在C++使用X&&传递会发生什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++使用X&&传递会发生什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

使用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_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

    不要有条件对对象实施移动操作。

到此,关于“C++使用X&&传递会发生什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI