问题描述
我重新开始使用 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++ 中的作用域和返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!