new和delete操作符
new和delete操作符
操作符 delete 和 delete[] 在释放对象存储空间的同时也会调用析构函数,而 free() 函数则不会调用析构函数。
#include<iostream>
using namespace std;
class test
{
public:
test(int i = 1)
{
num = i;
cout<<num<<" Constructor"<<endl;
}
~test()
{
cout<<num<<" Destructor"<<endl;
}
private:
int num;
};
int main()
{
test * t0 = new test(0);
test * t1 = new test[5];
test * t2 = (test *)malloc(sizeof(test));
cout << "t0 delete..." << endl;
delete t0;
cout << "t1 delete..." << endl;
delete[] t1;
cout << "t2 free..." << endl;
free(t2);
return 0;
}

本文探讨了C++中new、delete和delete[]操作符在创建和删除对象时的行为,重点指出delete和delete[]会调用析构函数,而free()则不会。通过实例展示了如何使用这些操作符并演示了构造函数和析构函数在内存管理中的作用。
3872

被折叠的 条评论
为什么被折叠?



