为什么返回对自动变量的引用有效? [英] Why does returning a reference to a automatic variable work?

查看:17
本文介绍了为什么返回对自动变量的引用有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

3.7.3 部分中的 C++ 标准草案 第 1 段 说:

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

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

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.

这篇关于为什么返回对自动变量的引用有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆