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.
这篇关于为什么返回对自动变量的引用有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么返回对自动变量的引用有效?


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01