强制引用不是“已更新”

问题描述:

我知道这可能是一个常见问题,而我之前也见过类似的问题。我试图围绕“通过const引用返回”东西来包装我的头。我似乎在这个看似简单的例子被卡住:强制引用不是“已更新”

#include <iostream> 
using namespace std; 

class Test { 
public: 
    int x; 

    Test(): x(0) {}; 

    const int& getX() const { 
    return x; 
    } 
}; 

int main() { 
    Test t; 
    int y = t.getX(); 
    cout << y << endl; 
    t.x = 1; 
    cout << y << endl; // why not 1? 
} 

我明白,const int的&返回防止我设置t.x使用类似y=1,这是罚款。然而,我希望y在最后一行是1,但它仍然为零,就好像getX()返回一个纯int。这里到底发生了什么?

+1

'y'本身仅会从'复制的getX()',不会使'y'参考。所以你的期望是错误的。 –

当你通过引用返回,你的安全,结果在整数y有没有关系,从这一点上成员x。它只是t.x的副本,它在初始化点后的值不会以任何方式取决于t.x的值或状态。

使用参考来观察你的期望行为:

#include <iostream> 
using namespace std; 

class Test { 
public: 
    int x; 

    Test(): x(0) {}; 

    const int& getX() const { 
    return x; 
    } 
}; 

int main() { 
    Test t; 
    const int &y = t.getX(); 
    cout << y << endl; 
    t.x = 1; 
    cout << y << endl; // Will now print 1 
} 

您将返回的const引用赋值给一个int变量,而您应该将它赋值给const int &如果您希望它被更新。现在它被复制。