1、编译器会对for循环优化,即for循环内的局部变量内存只分配一次,在for循环结束时回收内存。
变量的生命周期是在离开作用域时,生命就走到了尽头,但是变量所占的内存可能在变量的生命消失的时候还没有被回收。
void DoSomething(){
for(int i=0;i<5;i++){
int a=7;
printf("a=%x\n",&a);
}
}
结果是a的地址相同
a=bf98146c
a=bf98146c
a=bf98146c
a=bf98146c
a=bf98146c
说明在for循环中局部变量在for循环时分配内存,进入花括号时生命周期开始,在出花括号时生命周期结束,但是内存没有被回收,继续下一次循环时由于a的生命周期在上一次循环结束时结束,因而再一次定义a不会出现重复定义(作用域的关系),但此时不会为a分配内存,用上一次未被释放的内存。
当i=6时循环结束,回收内存。
2、函数中,变量的作用域与内存存在时间一样。
没有for循环的编译器优化
void fun()
{
{
int a=10;//bf914bfc
}//出作用域时内存被回收,因而2次的地址不同
int a=10;//bf914bf8
}
3、在循环中的局部变量内存只会在当前函数stack上分配一次,。
在每一次循环开始时,变量的构造函数首先被调用,在当前一轮循环结束时,变量的析构函数将被调用,而变量内存将被重复使用。
该变量内存将在当前函数退出时随stack清空而真正被回收注销
#include<iostream>
using namespace std;
class A
{
public:
A(){cout<<"in ctor of A"<<endl;}
A(A&){cout<<"in copy ctor of A"<<endl;}
~A(){cout<<"in dtor of A"<<endl;}
};
int main(int argc,char*argv[])
{
A x;
cout<<"before loop"<<endl<<endl;
for(int i=0;i<3;i++)
{
A a=x;
}
cout<<endl<<"after loop"<<endl;
return1;
}
in ctor of A
before loop
in copy ctor of A
in dtor of A
in copy ctor of A
in dtor of A
in copy ctor of A
in dtor of A
after loop
in dtor of A。