返回对本地或临时变量的引用

编程入门 行业动态 更新时间:2024-10-25 14:26:34
本文介绍了返回对本地或临时变量的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

查看下面的代码。我知道它不返回局部变量的地址,但为什么它仍然工作,并分配变量 i 在main()到'6'?

Look at the code below. I know it doesn't return the address of local variable, but why does it still work and assign the variable i in main() to '6'? How does it only return the value if the variable was removed from stack memory?

#include <iostream> int& foo() { int i = 6; std::cout << &i << std::endl; //Prints the address of i before return return i; } int main() { int i = foo(); std::cout << i << std::endl; //Prints the value std::cout << &i << std::endl; //Prints the address of i after return }

推荐答案

你很幸运。从函数返回不会立即擦除刚刚退出的堆栈框架。

You got lucky. Returning from the function doesn't immediately wipe the stack frame you just exited.

BTW,你怎么确认你有一个6回来?表达式 std :: cout<< & i ... 打印 i 的地址,而不是其值。

BTW, how did you confirm that you got a 6 back? The expression std::cout << &i ... prints the address of i, not its value.

更多推荐

返回对本地或临时变量的引用

本文发布于:2023-10-30 03:30:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541634.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!