[英]Why does std::move take rvalue reference as argument?
According to cppreference.com , move
has signature 根据cppreference.com ,
move
有签名
template< class T >
typename std::remove_reference<T>::type&& move( T&& t ) noexcept;
Why does it take a rvalue reference T&& t
as its arugment? 为什么它需要一个右值参考
T&& t
作为它的arugment?
Also when I tried the following code 当我尝试以下代码时
void foo(int&& bar) {
cout << "baz" << endl;
}
int main(){
int a;
foo(a);
}
I got an error from the compiler "an rvalue reference cannot be bound to an lvalue" 我从编译器得到一个错误“rvalue引用不能绑定到左值”
What is going on? 到底是怎么回事? I'm so confused.
我很困惑。
It's not an rvalue reference, but a forwarding reference ; 它不是右值引用,而是转发引用 ; which could preserve the value category of the argument.
这可以保留参数的值类别。 That means
std::move
could take both lvalue and rvalue, and convert them to rvalue unconditionally. 这意味着
std::move
可以同时使用左值和右值,并无条件地将它们转换为rvalue。
Forwarding references are a special kind of references that preserve the value category of a function argument, making it possible to forward it by means of std::forward.
转发引用是一种特殊的引用,它保留了函数参数的值类别,从而可以通过std :: forward转发它。 Forwarding references are either:
转发参考是:
1) function parameter of a function template declared as rvalue reference to cv-unqualified type template parameter of that same function template:
1)函数模板的函数参数,声明为对同一函数模板的cv-unqualified type模板参数的rvalue引用:
2) auto&& except when deduced from a brace-enclosed initializer list.
2)auto &&除了从括号括起的初始化列表中推断出来之外。
On the other hand, int&&
is an rvalue reference; 另一方面,
int&&
是一个右值引用; note the difference here, if a function template parameter has type T&&
with template parameter T
, ie a deduced type T
, the parameter is a forwarding reference. 注意这里的区别,如果函数模板参数具有带模板参数
T
类型T&&
,即推导类型T
,则该参数是转发引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.