您的位置:首页 > 其它

关于malloc/free与new/delete的区别

2012-10-23 14:56 435 查看
1.malloc/free是函数,C语言本身是不支持重载的。而new/delete是操作符。但是我们可以尝试重载它们:

void* operator new(std::size_t) throw (std::bad_alloc)
{
cout<<"重载版本,只抛出异常"<<endl;
throw bad_alloc();
}
void operator delete(void* p) throw()
{
}2.malloc拿到的,只是一个指针指向的一整块块地址,而new拿到的,却是一个一个的对象。可以认为,new是申请内存,并使用构造函数初始化了它们。
class Test
{
public:
Test(int i = 10):val(i){}
int val;
};

int main()
{
Test* pt1 = new Test;
cout<<pt1->val<<endl;
Test* pt2 = (Test*)malloc(sizeof(Test));
cout<<pt2->val<<endl;
return 0;
}我们会发现,使用new时,val被初始化为1,而使用malloc时,却是一个随机的数字。
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  delete class 语言 c