函数中局部变量的生命周期是否一定等于该函数执行的生命周期?
可能的重复:
优化 C++ 编译器如何重用堆栈函数的槽?
c++ 编译器有自己的方法来确定函数中每个局部变量的生命周期结束的时间,以便它们使用堆栈内存进行优化,或者简单地认为它等于生命周期 -函数执行的时间?
Possible Duplicate:
how does an optimizing c++ compiler reuse stack slot of a function?
do c++ compilers have their ways to determine the time at which, life-time of each local variable in a function ends so that they optimize using stack memory, or they simply take it equal to life-time of the function execution ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在函数返回之前,无法回收堆栈变量的内存。这是因为它们是特定调用的堆栈帧的一部分。返回指针位于它们下方,调用者的框架位于它们上方。显然,返回指针只有在函数返回之后才能被释放,因此堆栈变量就陷入了进退两难的境地,它们的内存在返回之前将保持不可用状态。
The memory for stack variables can't be reclaimed before the function has returned. This is because they are part of the stack frame for a particular call. The return pointer is below them, and the caller's frame is above them. Obviously, the return pointer cannot be freed until after the function returns, and so the stack variables are stuck between a rock and a hard place, so to speak, and their memory will remain unusable until after the return.
大多数编译器一次性为堆栈上的所有变量分配内存。例如:
在函数入口时为两个整数分配一次内存。然而,这是一个实现细节,对程序员来说是不可见的,并且两个变量 n 和 x 的生命周期并不相同。
Most compilers allocate the memory for all variables on the stack in one go. For example:
would allocate memory once, on function entry, for two integers. However, this is an implementation detail, not visible tto the programmer, and the lifetimes of the two variables n and x are not the same.