问题描述
我读过几篇关于&&我只是好奇如果有:
void fnc_1(int& p)
{
// ...
}
void fnc(int& r)
{
fnc_1(r); //我想/一世?调用它像这样:fnc_1(std :: forward(r))
}
fnc_1(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和完美转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!