C++11 左值、右值和 std::move()

2024-01-19

我有以下代码:

#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() and int&&是右值引用,我想知道为什么test(std::move(a)) and test(b) output lvalue?与签名匹配和函数重载有关吗?


输出should be:

lvalue.
rvalue
rvalue
lvalue.

右值表达式和类型为右值引用的表达式之间有一个非常重要的区别。的类型b是一个右值引用int,但是表达式b是左值;它是一个变量,你可以获取它的地址。这就是为什么最后一行输出是lvalue而不是rvalue。为了将其更改为右值,您应该调用std::move on it:

test(std::move(b));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++11 左值、右值和 std::move() 的相关文章

随机推荐