(转)delete和析构函数两者之间的联系

delete用于释放new在堆中动态生成的对象空间。
释放时会自动调用类的析构函数,在析构函数中用于释放类内部动态分配的得到的资源。
simple:
#include <iostream>
using std::cout;
using std::endl;
class Simple{
public:
Simple(){
p = new int; //使用new分配空间
*p = 10;
pArray = new int[*p]; //使用new分配数组空间
for(int i = 0; i < *p; i++)
pArray[i] = i;
}
~Simple(){
cout << "\ndisconstuctor\n" << "now delete p" << endl;
delete p;
cout << "now delete pArray" << endl;
delete [] pArray; //注意这里的释放配对
}
public:
void out(){
cout << "p value = " << *p << endl;
for(int i = 0; i < *p; i++)
{
cout << "array is " << *(pArray + i) << endl;
}
}
private:
//disable copy & assign control
Simple(const Simple&);
const Simple& operator=(const Simple&);
private:
int *p;
int *pArray;
};
int main()
{
Simple* s = new Simple; //生成堆对象
s->out();
delete s; //释放对象
return 0;
}
另外需要注意的是,请为多态基类定义一个虚析构函数,并不要在析构函数中调用virtual虚函数
程序中不要以Simple为例去自己管理指针成员,请使用auto_ptr或是tr1::share_ptr进行堆对象管理,这里的Simple只是一个晰构函数使用示例。
 
楼主要详细了解,看以看下相关资料:
《c++ primer》
5.11 new和delete表达式
18.1 优化内存分配
《thinking in c++》
chapter 13 动态对象创建
《effective c++》
条款16,条款49,50,51,52
《exception c++ style中文版》
条款22,23
等等。
这样会对c++ new delete有个比较深入的了解
posted @ 2015-07-21 16:46  川子61  阅读(741)  评论(0编辑  收藏  举报