1、malloc/free是函数,C语言本身是不支持重载的。
new/delete是操作符。但是我们可以尝试重载它们。
2、malloc拿到的只是一个指针指向的一整块地址,而new拿到的,却是一个一个的对象。
可以认为,new是申请内存,并使用构造函数初始化了它们。
#include "stdafx.h"
#include <cv.h>
using namespace std;
class Test
{
public:
Test(int i = 10) :val(i){}
int val;
};
//注意:使用new时,val被初始化为1,而使用malloc时,却是一个随机的数字。
int main()
{
Test* pt1 = new Test;
cout << pt1->val << endl;//10
Test* pt2 = (Test*)malloc(sizeof(Test));
cout << pt2->val << endl;//随机数:-842150451
return 0;
}
3、如果申请失败,malloc返回的指针为空,而new失败则会被抛出一个bad_alloc异常。所以我们通常这样使用new:
int main()
{
try
{
for (int i = 0; i < 100; i++)
{
char *p = new char[0x7fffffff];
}
}
catch (...)
{
cout << "something catched" << endl;
}
return 0;
}
而这样使用malloc:
int main()
{
double *ptr = (double*)malloc(sizeof(double) * 1000000000000);
if(ptr)
{
printf("we can use this pointer!");
}
else
printf("we can't use this pointer!");
return 0;
}
现在,我们大多数时候使用的都是C++的规则,而且new的优点也越发显现出来,因此经常会选择new/delete组合。
原文链接:http://blog.csdn.net/thefutureisour/article/details/8102927