析构函数和内存泄露问题

来源:百度知道 编辑:UC知道 时间:2024/06/13 18:27:37
#include "iostream.h"
#include "stdlib.h"
class Sample
{
public:
int x,y;
Sample() {x=y=0;}
Sample(int a, int b)
{x=a;y=b;}
void disp()
{
cout<<"x="<<x<<",y="<<y<<endl;
}
~Sample()
{
if(x==y)
cout<<"x=y"<<endl;
else
cout<<"x!=y"<<endl;
}
};

void main()
{
Sample s1(2,3);
s1.disp();
if(s1.x==2)
exit(0);
}
1.这个程序没有析构就退出了,会否产生内存泄露
2如果void main 改成int main()
最后用return 0 返回 结果是会调用析造函数(结果 x1 != x2)
那么是return前调用的吗?
3另外exit起什么作用的?在这里算是正常中止程序吗

回答:
1.分配的内存会在程序退出前释放,所以无所谓内存泄露的情况.

内存泄漏:程序运行时,产生了没法管理的非0指针.那么必然有段内存无法delete掉.

2.析构函数是在return前调用的.因为return已经是要返回操作系统了.

3.exit(0)就是退出程序吧,就想成是快速的退出程序(return 操作系统)吧.....我也不知道我这样说对了没.

MSDN:
When you call the exit or _exit functions, the destructors for any temporary or automatic objects that exist at the time of
the call are not called. An automatic object is an object that is defined in a function where the object is not declared to be static. A temporary object is an object created by the compiler. To destroy an automatic object before calling exit or _exit, explicitly call the destructor for the object, as follows:

myObject.myClass::~myClass();