C++ 中 delete 和 delete[] 的区别
一直对 C++ 中 delete 和 delete[] 的区别不甚了解,今天遇到了,上网查了一下,得出了结论。做个备份,以免丢失。
C++ 告诉我们在回收用 new 分配的单个对象的内存空间时用 delete, 回收用 new[] 分配的一组对象的内存空间时用 delete[].
关于 new[] 和 delete[],其中又分为两种情况:
① 为基本数据类型分配和回收空间;
② 为自定义类型分配和回收空间。
看下面程序,理解其中的区别
#include <iostream>
using namespace std;
class TEST {
public:
TEST() {
cout << "constructor called" << endl;
}
~TEST() {
cout << "destructor called" << endl;
}
};
int main() {
const int NUM = 3;
TEST *test1 = new TEST[NUM];
delete[] test1;
TEST *test2 = new TEST[NUM];
delete test2;
return 0;
}
运行结果如下:
![C++ 中 delete 和 delete[] 的区别 - mForestLaw - mForestLaws Blog](http://img0.ph.126.net/ey_96xb5bmziocRn1rcG9g==/3900398752379789130.jpg)
可见,当分配数组对象内存时用 delete[] 才能将所有数组对象销毁,而 delete 只能销毁数组中第一个对象

浙公网安备 33010602011771号