我对右值引用感到困惑,
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;
}
最佳答案
虽然a
可能看起来像一个右值,但事实并非如此。
a
本身就是一个包含右值引用的左值。
你可以获取a
的地址,但不能获取move(a)
的地址。
请看一下这个article真正了解专门针对您的问题的值(value)类别。
关于C++ 右值引用请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59296568/