当变量从内存在C ++中删除? [英] When are variables removed from memory in C++?
问题描述
我一直使用C ++了一点吧。我只是从来没有肯定的内存管理是如何工作的,所以这里有云:
I've been using C++ for a bit now. I'm just never sure how the memory management works, so here it goes:
我首先不确定的内存是如何在一个未分配的功能,例如:
I'm first of all unsure how memory is unallocated in a function, ex:
int addTwo(int num)
{
int temp = 2;
num += temp;
return num;
}
因此,在这个例子中,将温度从存储器函数结束后删除?如果没有,这是怎么完成的。在C#中,一旦其范围使用一个变量被删除。是否有其他之情况下,我应该知道的?
So in this example, would temp be removed from memory after the function ends? If not, how is this done. In C# a variable gets removed once its scope is used up. Are there also any other cases I should know about?
感谢
推荐答案
局部变量温度
是在功能和开始时的堆栈上推,杀出堆栈当函数退出。
The local variable temp
is "pushed" on a stack at the beginning of the function and "popped" of the stack when the function exits.
下面是从非优化的版本拆卸:
Here's a disassembly from a non optimized version:
int addTwo(int num)
{
00411380 push ebp
00411381 mov ebp,esp //Store current stack pointer
00411383 sub esp,0CCh //Reserve space on stack for locals etc
00411389 push ebx
0041138A push esi
0041138B push edi
0041138C lea edi,[ebp-0CCh]
00411392 mov ecx,33h
00411397 mov eax,0CCCCCCCCh
0041139C rep stos dword ptr es:[edi]
int temp = 2;
0041139E mov dword ptr [temp],2
num += temp;
004113A5 mov eax,dword ptr [num]
004113A8 add eax,dword ptr [temp]
004113AB mov dword ptr [num],eax
return num;
004113AE mov eax,dword ptr [num]
}
004113B1 pop edi
004113B2 pop esi
004113B3 pop ebx
004113B4 mov esp,ebp //Restore stack pointer
004113B6 pop ebp
004113B7 ret
推和杀出的条款内容只是作为一个比喻。正如你可以从汇编输出看一下编译器从堆栈指针减去一个合适的值保留局部变量等一气呵成的所有内存。
The terms "pushed" and "popped" are merely meant as an analogy. As you can see from the assembly output the compiler reserves all memory for local variables etc in one go by subtracting a suitable value from the stack pointer.
这篇关于当变量从内存在C ++中删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!