#include <string> #include <iostream> using namespace std; class Student { public: int num ; string strname; Student(int num,string name) { this->num=num; this->strname=name; } ~Student() { cout<<"num:"<<this->num<<"name"<<this->strname<<endl; } }; |
int _tmain(int argc, _TCHAR* argv[]) Student stu1(1,"Li Ming");//对象定义在栈上,所以程序结束时会自动析构哦; //(1)
} |
上面两种定义都定义了对象,但是执行结果是下面的:
上面没有调用delete删除堆上的对象,所以程序即使结束了,对象是不会自动析构的,这就产生了垃圾;如何这些是一些资源文件或者内核对象,你的程序迟早挂掉;
在(1)处加入delete pstu2;
所以,使用类定义的对象是能够自动析构的;使用类通过new出来的对象,是需要delete的,你不delete,你SOCKET、多线程编程会出问题的。