首页 > 编程 > C++ > 正文

C++中delete和delete[]的区别

2019-11-06 06:33:49
字体:
来源:转载
供稿:网友

用 new 创建的对象用 delete 回收,用 new[] 创建的对象用 delete[] 回收。

基本类型的对象没有析构函数,所以基本类型组成的数字空间都可以用 delete 或者 delete[] 回收;

对于类对象数组,只能用delete[];

对于 new 的单个对象,只能用delete。

class A{public: A(){ cout<<"constructor"<<endl; } ~A(){ cout<<"destructor"<<endl; }};int mian( void ){ int num = 5; A * c1 = new A[ num ]; cout<<hex<<c1<<endl; delete c1; A * c2 = new A[ num ]; cout<<hex<<c2<<endl; delete[] c2; return 0;}

当使用 delete 去回收类数组空间时,只回收了c[0]。这就是问题所在。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选