#include<iostream>
#include<string>
using namespace std;
void Test_1()
{
int *p = (int *)malloc(sizeof(int));
*p = 10;
if (NULL == p)
exit(1);
free(p);
int *q = new int(10);
delete q;
int *q_2 = new int[10];
delete[] q_2;
}
/*
为什么说 new delete(c++)比 malloc free(c) 更加的强悍
1.new 与 malloc 的比较
(1)malloc开辟空间时需要进行空间大小的计算,new不需要
(2)malloc空间开辟成功后需要强制转换,new不需要
(3)malloc空间开辟后需要对是否成功开辟进行检测,new不需要
(4)malloc只是对空间的开辟,不进行初始化,new可以在空间开辟时进行初始化
(5) malloc开辟空间时只是开辟相应空间的大小,没有单个元素与数组的区别
对于 new 而言开辟数组空间时,必须用 new[],释放数组空间时必须用 delete[]
*/
class Date
{
public:
Date(int x = 0) :date(x)
{
p = (char*)malloc(sizeof(char)* 10);
cout << "This is Date()" << endl;
}
~Date()
{
free(p);
cout << "This is ~Date()" << endl;
}
public:
int date;
char *p;
};
void Test_2()
{
Date *d1 = (Date*)malloc(sizeof(Date));
d1->date = 10;
free(d1);
Date *d2 = new Date(10);
delete d2;
}
void main()
{
Test_2();
}
/*
2.最主要的区别
对于对象而言
malloc 只管开辟相应类空间的大小 free 只是释放相应空间
new 在开辟相应类空间大小的同时会调用该类的构造函数
delete 在释放相应类空间的同时会调用该类的析构函数*/
本文出自 “10747227” 博客,转载请与作者联系!
原文:http://10757227.blog.51cto.com/10747227/1729055