我读过几篇关于&&我只是好奇如果有:
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和完美转发
发布评论