Rvalue ref和完美转发

编程入门 行业动态 更新时间:2024-10-10 04:20:03
本文介绍了Rvalue ref和完美转发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我读过几篇关于&&我只是好奇如果有:

void fnc_1(int& p) { // ... } void fnc(int& r) { fnc_1(r); //我想/一世?调用它像这样:fnc_1(std :: forward(r))}

fnc_1(r)只要传递'r'就足够了?

r 是一个左值,就像任何其他变量,不管类型。是的,没错,命名的右值引用是左值,而不是右值。

fnc_1(std :: forward(r))也不会编译,因为 std :: forward 是专门设计为不推断其模板参数。

要传递右值,以下任何一个都可以工作:

fnc_1(std :: move(r)) fnc_1(std :: forward< int&&>(r)) fnc_1(std :: forward< int>(r))

使用 std :: move 是将lvalue转换为右值的惯用方法,因此我建议使用。

I've read few papers about && and I'm just curious if having:

void fnc_1(int&& p) { //... } void fnc(int&& r) { fnc_1(r);//am I suppose to/should I? call it like so:fnc_1(std::forward(r)) }

or just passing 'r' is enough?

解决方案

fnc_1(r) won't compile, because r is an lvalue, just like any other variable, regardless of type. Yes, that's right, named rvalue references are lvalues, not rvalues.

fnc_1(std::forward(r)) also won't compile, because std::forward is specifically designed not to infer its template argument.

To pass an rvalue, either of the following would work:

fnc_1(std::move(r)) fnc_1(std::forward<int&&>(r)) fnc_1(std::forward<int>(r))

Using std::move is the idiomatic way to cast an lvalue to an rvalue, so I would recommend using that.

更多推荐

Rvalue ref和完美转发

本文发布于:2023-11-03 23:44:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556409.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:完美   Rvalue   ref

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!