【发布时间】:2013-08-26 21:46:07
【问题描述】:
我目前正在阅读有关 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。
【问题讨论】:
-
因为它是未定义的行为,它看起来可以正常工作,但稍后会中断,不能依赖它。
-
可能发生的事情(同样,对于 UB,任何事情都会发生)是因为在你调用
Add之后,你没有调用其他任何东西,还没有任何东西覆盖 @987654325 所在的那块内存@ 是,所以旧值仍然存在。话虽如此,你不能依赖这种情况总是发生。 -
这两个 cmets 应该都是答案
-
通常会在堆栈再次增长时被覆盖。调用 Factorial(50) 的递归实现,当你使用它时我最好它会死
-
@DanF 好的,我会回答的。
标签: c++ reference return undefined-behavior