参考链接:https://www.cnblogs.com/whwywzhj/p/7905176.html
课本的解释:
情况1:
int *a = new int[10];
delete a; //方式1
delete [] a; //方式2
此时两种释放的效果是相同的。因为分配内存时,内存大小已经确定,系统可以记忆并且进行管理,在析构时,系统并不会调用析构函数,它直接通过指针可以获取实际分配的内存空间,哪怕是一个数组内存空间。
情况2,针对类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];
delete a; //仅释放了a指针指向的全部内存空间 但是只调用了a[0]对象的析构函数 剩下的从a[1]到a[9]这9个用户自行分配的m_cBuffer对应内存空间将不能释放 从而造成内存泄漏
delete [] a; //调用使用类对象的析构函数释放用户自己分配内存空间并且释放了a指针指向的全部内存空间
总结:
关于 new[] 和 delete[],其中又分为两种情况:
(1) 为基本数据类型分配和回收空间,delete[] 和 delete 是等同的。
(2) 为自定义类型分配和回收空间。 这时情况就发生了变化。
具体例子如下:
#include <iostream>
using namespace std;
/class Babe
class Babe
{
public:
Babe()
{
cout << \"Create a Babe to talk with me\" << endl;
}
~Babe()
{
cout << \"Babe don\'t go away,listen to me\" << endl;
}
};
//main function
int main()
{
Babe* pbabe = new Babe[3];
delete pbabe;
pbabe = new Babe[3];
delete pbabe[];
return 0;
}
结果是:
Create a babe to talk with me
Create a babe to talk with me
Create a babe to talk with me
Babe don\'t go away,listen to me
Create a babe to talk with me
Create a babe to talk with me
Create a babe to talk with me
Babe don\'t go away,listen to me
Babe don\'t go away,listen to me
Babe don\'t go away,listen to me
容易造成的问题:
所以,在用这些类生成对象数组时,用delete[]来释放。用delete来释放会有隐患。