我目前正在阅读有关 C++ 的内容,我读到当使用按引用返回时,我应该确保我不会返回对将超出范围的变量的引用函数返回。
那么,为什么在 Add
函数中对象 cen
是通过引用返回的,而且代码工作正常?!
代码如下:
#include <iostream>
using namespace std;
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
int GetCents() { return m_nCents; }
};
Cents& Add(Cents &c1, Cents &c2)
{
Cents cen(c1.GetCents() + c2.GetCents());
return cen;
}
int main()
{
Cents cCents1(3);
Cents cCents2(9);
cout << "I have " << Add(cCents1, cCents2).GetCents() << " cents." << std::endl;
return 0;
}
我在 Win7 上使用 CodeBlocks IDE。
最佳答案
这是 undefined behavior , 它可能看起来工作正常,但它可能随时中断,您不能依赖该程序的结果。
当函数退出时,用于保存自动变量的内存将被释放,引用该内存将无效。
C++ 标准草案 3.7.3
paragraph 1 说:
Block-scope variables explicitly declared register or not explicitly declared static or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.
关于c++ - 为什么返回对自动变量的引用有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18409639/