C++ 中的作用域和返回值

2023-10-17C/C++开发问题
1

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6