我遇到了一个关于使用引用数据成员的示例源代码,但我对输出感到困惑。这是示例代码。
class Test {
private:
int &t;
public:
Test (int y):t(y) { }
int getT() { return t; }
};
int main() {
int x = 20;
Test t1(x);
cout << t1.getT() << "\n"; // Prints 20 as output. however y has already been destroyed but still prints 20.
x = 30;
cout << t1.getT() << endl; // Prints Garbage as output Why ? Ideally both steps should be Garbage.
return 0;
}
为了增加更多的混淆,这里还有一段代码用于同一个类
int main() {
int x = 20;
int z = 60;
Test t1(x);
Test t2(z);
cout<<t1.getT()<<"\n"; // Prints 60! WHY? Should print garbage
cout<<t2.getT() << "\n"; // Prints Garbage
cout<<t1.getT() << endl; // Prints Same Garbage value as previous expression
return 0;
}
最佳答案
x
使用临时值 按值 传递,因此 t
是对 的引用临时,不是x
。该临时对象将在构造函数返回后被销毁。您的代码有未定义的行为。任何东西都可以作为输出出现。您的问题可以通过传递对 x
的引用来解决,例如
Test (int& y):t(y);
但这不是一个好主意。可能会出现 x
超出范围但仍在使用 Test
对象的情况,然后会出现相同的问题。
关于c++ - reference(&) 数据成员指向堆栈变量的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24260693/