返回&和没有区别是什么?

use*_*499 0 c++

我仍然没有弄清楚&编译器中的工作原理。

为了弄清楚,我尝试分解下面的代码:

private:
        int data;
public:
int& at()
{
    return data;
}
int at()
{
    return data;
}

const int& result = mymay.at(); //call the two functions
Run Code Online (Sandbox Code Playgroud)

我发现int& at()返回一个地址,并int at()返回一个值;编译器首先将值写入内存,然后将“结果”的地址设置为该地址。所以我知道这int at()将返回一个副本。我也了解写作是最佳实践friend ostream& operator<<(ostream &os , const A &obj)

但我想知道是否正确:在以下代码中,A &get1()返回l-value,然后A get2()返回r-value

#include <iostream>
using namespace std;
class A
{
public:
    A &get1(){
        return *this;
    }
    A get2(){
        return *this;
    }
    friend ostream& operator<<(ostream &os , A &obj){
        cout<<"An l-value function called."<<endl;
        return os;
    }
    friend ostream& operator<<(ostream &os , A &&obj){
        cout<<"An r-value function called."<<endl;
        return os;
    }
};
int main()
{
    A tmp;
    cout<<"get1: "<<tmp.get1()<<"get2: "<<tmp.get2()<<endl;
    return 0;
}

Run Code Online (Sandbox Code Playgroud)

实际结果:

An l-value function called.
An r-value function called.
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 6

at返回引用的版本允许您data通过该引用修改成员数据:

mymay.at() = 1;
Run Code Online (Sandbox Code Playgroud)

将设置data在实例mymay为1所以mymay.at()1-值:即,它可以被放置在分配的左手边。

at返回值的版本将不允许您执行该操作。它不是l值


第二点,左不能绑定到匿名临时可以引用右值引用。您的重载分辨率是明确的,它可以说明程序的输出。&&cout