左值和右值引用

问题描述 投票:0回答:1

我很难理解左值和右值引用。看这个代码示例

#include <iostream>

//Returns r-value
int Add(int x, int y) {
    return x + y;
}
//Return l-value
int & Transform(int &x) {
    x *= x;
    return x;
}

void Print(int &x) {
    std::cout << "Print(int&) L value ref" << std::endl; 
}
void Print(const int &x) {
    std::cout << "Print(const int&) const l value ref" << std::endl;

}
void Print(int &&x) {
    std::cout << "Print(int &&) r value ref" << std::endl;
}
int main() {
    //x is lvalue
    int x = 10;
    
    //ref is l-value reference
    int &ref = x ;
    //Transform returns an l-value
    int &ref2 = Transform(x) ;
    //Binds to function that accepts l-value reference
    Print(x);

    Print(ref);
    Print(ref2);

    //rv is r-value reference
    int &&rv = 8 ;
    
    //Add returns a temporary (r-value)
    int &&rv2 = Add(3,5) ;
    //Binds to function that accepts a temporary, i.e. r-value reference
    Print(3);
    Print(rv);
    Print(rv2);
    return 0;
}

当我运行这个时,我得到了

Print(int&) L value ref
Print(int&) L value ref
Print(int&) L value ref
Print(int &&) r value ref
Print(int&) L value ref
Print(int&) L value ref

我可以(我猜)理解前 4 个。但是对于最后两个,我正在打印

rv
rv2
,我认为它们是 r 值,那么为什么它们被传递给 Lvalue ref 函数?

c++ c++11 rvalue-reference
1个回答
1
投票

rv
rv2
实际上是左值,因为它们已分配有名称。它们的类型是 r 值引用。

第一个

Print()
采用常量引用,它可以绑定到左值和右值。要调用第二个
Print()
,您必须使用
std::move()
rv
rv2
转换为正确的 r 值,例如:

Print(std::move(rv));
Print(std::move(rv2));
© www.soinside.com 2019 - 2024. All rights reserved.