C ++ 11左值,右值和std :: move() [英] C++11 lvalue, rvalue and std::move()
问题描述
我有以下代码:
#include <iostream>
using namespace std;
void test(int& a) {
cout << "lvalue." << endl;
}
void test(int&& a) {
cout << "rvalue" << endl;
}
int main(int argc, char *argv[]) {
int a = 1;
int&& b = 2;
test(a);
test(1);
test(std::move(a));
test(b);
}
输出:
lvalue.
rvalue
lvalue.
lvalue.
std :: move()
和 int&&
是右值引用,我想知道为什么 test(std :: move(a))
和 test(b)
输出 lvalue
?它与签名匹配和函数重载有关吗?
std::move()
and int&&
are rvalue references, I wonder why test(std::move(a))
and test(b)
output lvalue
? Is it related with signature matching and function overloading?
推荐答案
输出应该为:
lvalue.
rvalue
rvalue
lvalue.
作为右值的表达式与类型为右值的表达式之间有一个非常重要的区别参考。 b
的类型是对 int
的右值引用,但表达式为 b
是一个左值;它是一个变量,您可以获取其地址。这就是为什么输出的最后一行是 lvalue
而不是 rvalue
的原因。为了将其更改为右值,应在其上调用 std :: move
:
There is a very important distinction to be made between expressions which are rvalues and expressions whose type is an rvalue reference. The type of b
is an rvalue reference to int
, but the expression b
is an lvalue; it is a variable, you can take its address. This is why the final line of output is lvalue
rather than rvalue
. In order to change it to an rvalue, you should call std::move
on it:
test(std::move(b));
这篇关于C ++ 11左值,右值和std :: move()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!