关于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;
}
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;
}
相关文章推荐
- 关于 C++ 的 new、delete 与 C 的 malloc、free 的区别
- malloc/free和new/delete的主要区别以及c与c++关于结构体定义使用的区别
- 概念:malloc/free与new/delete的区别
- new/delete 和 malloc/free 的区别
- new/delete 与 malloc/free的区别是什么?
- new/delete 与malloc/free 区别与联系
- C++中malloc/free与new/delete的区别及内存分配失败错误处理
- C语言 malloc/free和C++中new/delete的区别
- malloc/free与new/delete的区别
- malloc/free与new/delete的使用方法与区别
- new/delete和malloc/free的一般区别
- 动态内存分配- new/delete 和malloc/free的区别
- new\delete,malloc\free的区别
- 百度笔试题:malloc/free与new/delete的区别
- new/delete 和malloc/free 的区别
- new/delete和malloc/free的区别
- malloc/free与new/delete的区别
- new delete和malloc free的用法与区别
- malloc/free与new/delete的区别
- malloc/free 与new/delete的区别