new delete
C:malloc、calloc、realloc、free
1.malloc、calloc区别:malloc只申请空间不会初始化,calloc申请空间,并给申请的空间初始化。malloc、calloc传递参数有不同。
2.Realloc:重新申请空间。
C++:new、delete
1.new、delete与malloc、calloc、realloc、free区别:
New申请空间后,还会调用构造函数进行初始化,malloc、calloc、realloc没有;Delete在释放空间之前,会调用析构函数。
2.New申请的空间只能由delete释放;malloc、calloc、realloc申请的空间只能由Free进行释放。
class Test
{
public:
Test()
{
cout<<"Test::Test()"<<endl;
m_data = 0;
}
~Test()
{
cout<<"Test::~Test()"<<endl;
}
private:
int m_data;
};
void main()
{
int *ptr = (int*)malloc(sizeof(int) * 10);
assert(ptr != NULL);
free(ptr);
int *ptr1 = (int*)calloc(10, sizeof(int));
assert(ptr1 != NULL);
free(ptr);
//realloc();
Test *pt = (Test*)malloc(sizeof(Test));
free(pt); //只申请空间
Test *pt = new Test; //1申请空间 2 调用构造函数
delete pt; //1调用析构函数 2释放空间
int *ptr = new int;
delete ptr;
int *ptr1 = new int(10); //申请空间,调用构造函数初始化
delete ptr1;
Test *pt1 = new Test[10]; //申请数组
delete []pt1; //数组空间的释放
}