为什么 std::move 将右值引用作为参数?

Why does std::move take rvalue reference as argument?

根据cppreference.commove有签名

template< class T >
typename std::remove_reference<T>::type&& move( T&& t ) noexcept;

为什么它采用右值引用 T&& t 作为其参数?

同样当我尝试下面的代码时

void foo(int&& bar) {
    cout << "baz" << endl;
}

int main(){
    int a;
    foo(a);
}

编译器出错"an rvalue reference cannot be bound to an lvalue"

这是怎么回事?我很困惑。

这不是右值引用,而是forwarding reference;这可以保留参数的值类别。这意味着 std::move 可以接受左值和右值,并无条件地将它们转换为右值。

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. 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:

2) auto&& except when deduced from a brace-enclosed initializer list.

另一方面,int&& 是右值引用;请注意此处的区别,如果函数模板参数的类型为 T&&,模板参数为 T,即推导类型 T,则该参数为转发引用。