C ++中的范围和返回值 [英] Scope and return values in C++

查看:141
本文介绍了C ++中的范围和返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用c ++重新开始,正在考虑变量的范围。
如果我在一个函数里面有一个变量,然后返回那个变量,那么当它返回时,变量不会死,因为它所在的范围已经结束了。

I am starting again with c++ and was thinking about the scope of variables. If I have a variable inside a function and then I return that variable will the variable not be "dead" when it's returned because the scope it was in has ended?

我试过这个函数返回一个字符串,它的确工作。
任何人都可以解释这个?

I have tried this with a function returning a string and it did work. Can anyone explain this? Or at least point me to some place that can explain this to me please.

感谢

推荐答案


当函数终止时,
会在以下步骤后发生:

When the function terminates, the following steps happen:


    <

    函数的返回值是
    复制到
    的占位符中。为了这个目的,

  • The function’s return value is copied into the placeholder that was put on the stack for this purpose.

堆栈框架
指针被弹出。这会破坏
所有局部变量和参数。

Everything after the stack frame pointer is popped off. This destroys all local variables and arguments.

返回值从
堆栈中弹出并分配为值
的函数。如果
函数的值没有赋给任何东西,
不会赋值,而
的值会丢失。

The return value is popped off the stack and is assigned as the value of the function. If the value of the function isn’t assigned to anything, no assignment takes place, and the value is lost.

要执行的下一条指令
的地址从堆栈中弹出
,CPU将以
的指令恢复执行。

The address of the next instruction to execute is popped off the stack, and the CPU resumes execution at that instruction.

堆栈和堆

这篇关于C ++中的范围和返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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