为什么返回一个自动变量的引用工作?

问题描述:

我目前正在阅读关于 C ++ ,并且我读到当使用通过引用返回时,我应该确保我不返回一个将超出范围的引用,当函数返回。

I'm currently reading about C++, and I read that when using return by reference I should make sure that I'm not returning a reference to a variable that will go out of scope when the function returns.

那么为什么在 Add 函数中对象 cen 通过引用返回,代码工作正常?

So why in the Add function the object cen is returned by reference and the code works correctly?!

以下是代码:

#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。

I am using CodeBlocks IDE over Win7.

这是未定义的行为 ,它可能似乎正常工作,但它可以在任何时候中断,你不能依赖于此程序的结果。

This is undefined behavior, it may seem to work properly but it can break at anytime and you can not rely on the results of this program.

当函数退出时,用于保持的内存

When the function exits, the memory used to hold the automatic variables will be released and it will not be valid to refer to that memory.

部分中的C ++标准草案3.7.3

The draft C++ standard in section 3.7.3 paragraph 1 says:


块范围变量显式声明的寄存器或未明确声明static或extern具有自动存储持续时间。 这些实体的存储空间持续到创建它们的块退出。