我开始学习有关右值的参考。我试图理解我的代码,但我不懂一行,为什么对左值而不是右值使用函数。
#include <iostream>
void reference_fun(int &k) {
std::cout << "reference to lvalue (object) = " << k << std::endl;
}
void reference_fun(int &&k) {
std::cout << "reference to rvalue (temporary) = " << k << std::endl;
}
void test2(int &&k) {
//rvalue in the body of the function becomes lvalue
reference_fun(k);
reference_fun(std::move(k));
}
int main() {
int obj = 10;
int &&rvalue = 10 + 10;
reference_fun(obj); /* result as function to lvalue */
reference_fun(321); /* result as function to rvalue */
reference_fun(321 + 3); /* result as function to rvalue */
reference_fun(rvalue); // I don't understand the result of this line, why is used function to lvalue, when rvalue is int && ?
test2(14 + 10); /* result as function to lvalue and rvalue */
// test2(rvalue); //compilation error
return 0;
}
这是我的输出:
reference to lvalue (object) = 10
reference to rvalue (temporary) = 321
reference to rvalue (temporary) = 324
reference to lvalue (object) = 20 //this line ?
reference to lvalue (object) = 24
reference to rvalue (temporary) = 24
我对此行有疑问:reference_fun(rvalue);
当我将void reference_fun(int &k);
定义为void reference_fun(int &&k);
时为何使用rvalue
而不使用int&&
吗?