此C ++代码:
void f(int& i) {
cout << "by reference" << endl;
}
void f(const int& i) {
cout << "by const reference" << endl;
}
void f(int&& i) {
cout << "by rvalue reference" << endl;
}
int main() {
int x;
const int y = 5;
cout << "f(x): ";
f(x);
cout << "f(y): ";
f(y);
cout << "f(x+y): ";
f(x+y);
cout << "f(move(x)): ";
f(move(x));
cout << "f(move(y)): ";
f(move(y));
cout << "f(move(x+y)): ";
f(move(x+y));
}
打印:
f(x): by reference
f(y): by const reference
f(x+y): by rvalue reference
f(move(x)): by rvalue reference
f(move(y)): by const reference
f(move(x+y)): by rvalue reference
我理解除第五行之外的所有行:为什么“ move(y)”不使编译器使用右值引用选择f的重载?以及如何使编译器选择此变体?
为什么“ move(y)”不使编译器使用右值引用选择f的重载
因为int &&
是非常量引用,并且参数是const
。
以及如何使编译器选择此变体?
通过将功能参数更改为const int &&
(或通过从const
中删除y
),
但是通常您不想使用const
右值引用。移动的全部目的是从要移动的对象中窃取资源。如果对它的引用是const
,则不能执行此操作。