c++ - 为什么返回对自动变量的引用有效?

标签 c++ reference return undefined-behavior

我目前正在阅读有关 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/

相关文章:

javascript - 在使用 Javascript 的表单中使用 onsubmit 时,需要显式 "return"关键字吗?

return - 如何从 Nim 的主 block 返回退出代码?

c++ - 有条件地启用一个子类型(类似于enable_if来启用功能)

c++ - 为什么在指定 -std=gnu++11 时使用 C++98?

c++ - 两个版本的函数可以重载,常量成员函数和不带 const 的函数

python - 如何将对象交给 python 垃圾回收?

c++ - 转换对基类的引用 : standard behaviour?

c++ - 令人困惑的输出

c++ - 使用整数存储许多 bool 值是否值得?

c++ - 将 std::future 移动到另一个 std::future