delete和delete [] 的真正区别
2017-12-20
针对简单类型
int *a = new int[10];
delete a;
delete [] a;
这两种都不会存在内存泄漏,原因在于:分配简单类型内存时,内存大小已经确定,系统可以记忆并且进行管理,在析构时系统不会调用析构函数。
它直接通过指针可以获取实际分配的内存空间,哪怕是一个数组内存空间。
针对Class类型
class A {
private:
char *m_cBuffer;
int m_nLen;
public:
A() {m_cBuffer = new char[m_nLen];}
~A() {delete [] m_cBuffer;}
}
A *a = new A[10];
delele a;
delete a仅仅释放了a指针指向的全部内存空间,但是只调用了a[0]对象的西沟函数,剩下的从a[1]到a[9]这9个用户自行分配的m_cBuffer对应内存空间将不能释放,从而造成内存泄漏。
delete [] a 调用使用类对象的西沟函数释放用户自己分配内存空间并且释放了a指针指向的全部内存空间。
程序验证
#include <iostream>
using namespace std;
class Base {
public:
Base() {cout<<"Create a Base to talk with me"<<endl;}
~Base() {cout<<"Base don not go away, listen to me"<<endl;}
}
int main() {
/*
Base *pbase = new Base[3];
delete pbase;
*/
Base *pBase = new Base[3];
delete [] pbase;
return 0;
}