有static局部对象的函数析构函数的调用有关问题
有static局部对象的函数析构函数的调用问题
#include <iostream>
using namespace std;
class box
{public:
~box(){cout<<"destructed called "<<height<<endl;}
box(int h=10,int w=12,int len=15):height(h),width(w),length(len){}
int volume() ;
private:
int height;
int width;
int length;
};
int box::volume()
{return(height*width*length);}
int main()
{ static box a[2]={
box(1,2,3),
box(2,3,4)
};
cout<<"the volume a[0] is "<<a[0].volume()<<endl;
cout<<"the volume a[1] is "<<a[1].volume()<<endl;
return 0;
}
上述程序的结果是:the volume a[0] is 6
the volume a[1] is 24
destructed called Press any key to continue
如果把上面程序中的static 去掉,结果是:the volume a[0] is 6
the volume a[1] is 24
destructed called 2
destructed called 1
Press any key to continu
我的问题是为什么有static的结果是那样的呢?
------解决方案--------------------
static 声明的对象其内存不在当前函数的"栈"上。
所以函数出栈的时候,不会调用析构函数。
------解决方案--------------------
可能vc6在全局变量析构之前就关闭了界面打印功能吧,所以你那俩析构的时候是打印了,可没显示出来。你要不到析构函数里加断点试试,都进了就代表析构了呗。
------解决方案--------------------
大哥,你别在main里测这个东西啊。
main函数结束,全局的东西也会析构的。
给你简单改了下。
用这个看更直观。
#include <iostream>
using namespace std;
class box
{public:
~box(){cout<<"Destroy box "<<m_Num<<endl;}
box(int Num):m_Num(Num){}
private:
int m_Num;
};
void fun()
{
static box a[2]={
box(1),
box(2)
};
}
void fun1()
{
box a[2]={
box(3),
box(4)
};
}
int main()
{
fun();
fun1();
system("pause");
return 0;
}
#include <iostream>
using namespace std;
class box
{public:
~box(){cout<<"destructed called "<<height<<endl;}
box(int h=10,int w=12,int len=15):height(h),width(w),length(len){}
int volume() ;
private:
int height;
int width;
int length;
};
int box::volume()
{return(height*width*length);}
int main()
{ static box a[2]={
box(1,2,3),
box(2,3,4)
};
cout<<"the volume a[0] is "<<a[0].volume()<<endl;
cout<<"the volume a[1] is "<<a[1].volume()<<endl;
return 0;
}
上述程序的结果是:the volume a[0] is 6
the volume a[1] is 24
destructed called Press any key to continue
如果把上面程序中的static 去掉,结果是:the volume a[0] is 6
the volume a[1] is 24
destructed called 2
destructed called 1
Press any key to continu
我的问题是为什么有static的结果是那样的呢?
class
iostream
------解决方案--------------------
static 声明的对象其内存不在当前函数的"栈"上。
所以函数出栈的时候,不会调用析构函数。
------解决方案--------------------
可能vc6在全局变量析构之前就关闭了界面打印功能吧,所以你那俩析构的时候是打印了,可没显示出来。你要不到析构函数里加断点试试,都进了就代表析构了呗。
------解决方案--------------------
大哥,你别在main里测这个东西啊。
main函数结束,全局的东西也会析构的。
给你简单改了下。
用这个看更直观。
#include <iostream>
using namespace std;
class box
{public:
~box(){cout<<"Destroy box "<<m_Num<<endl;}
box(int Num):m_Num(Num){}
private:
int m_Num;
};
void fun()
{
static box a[2]={
box(1),
box(2)
};
}
void fun1()
{
box a[2]={
box(3),
box(4)
};
}
int main()
{
fun();
fun1();
system("pause");
return 0;
}