Why does returning a reference to a automatic variable work?(为什么返回对自动变量的引用有效?)
问题描述
我目前正在阅读有关 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.
这篇关于为什么返回对自动变量的引用有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么返回对自动变量的引用有效?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
