我对右值引用感到困惑,is_rvalue_reference<decltype(a)>::value
表示a
变量是右值参考,但无法将其传递给hello(int &&)
函数。
#include <iostream>
#include <string>
#include <array>
using std::cout;
using std::endl;
using std::boolalpha;
using std::string;
using std::is_rvalue_reference;
using std::move;
void hello(int && z) {};
int main(void) {
int && a = 20;
// a is_xvalue: true
cout << "a is_xvalue: " << boolalpha << is_rvalue_reference<decltype(a)>::value << endl;
// error C2664:
// 'void hello(int &&)': cannot convert argument 1 from 'int' to 'int &&'
hello(a);
// compile ok.
hello(move(a));
return 0;
}
[Types和value categories是两个独立的事物。
每个C ++表达式(具有其操作数,文字,变量名等的运算符)的特征在于两个独立的属性:type和value category。
a
的类型是int&&
,即右值参考。但是a
作为命名变量,是左值,不能绑定到右值引用。似乎令人困惑,但请尝试将它们分开考虑。
(重点是我的)
以下表达式是左值表达式:
- 变量的名称,函数,模板参数对象(自C ++ 20起)或数据成员,无论类型如何,例如std :: cin或std :: endl。 即使变量的类型是右值引用,由名称组成的表达式是左值表达式;