Rvalue ref和完美转发 [英] Rvalue ref and perfect forwarding

查看:198
本文介绍了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和完美转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆