new/delete和malloc/free区别
这篇文章会分几点讲一下new和malloc的区别
1、性质
new/delete是C++的运算符,而malloc/free是C的库函数
2、参数
new无需指定大小,malloc需要指定大小
3、返回值类型
new的返回值类型是对象指针,malloc返回值类型是void *
4、在类中的使用
new会调用构造函数和析构函数,malloc不会调用
5、开辟空间失败
new是通过抛出bad_alloc类型的异常来判断的
malloc是通过返回值和nullptr作比较来判断的
6、内存泄漏
new可以精准到行,而malloc是直接报错
7、开辟空间
new可以对开辟的内存进行初始化操作,malloc不行
我们再利用代码观察一下
普通数据类型:
int *p = (int*)malloc(sizeof(int));
if(p == nullptr)
{
return -1;
}
*p = 20;
free(p);
try
{
int *p1 = new int(20);
}
catch();
delete p1;
数组:
int *q = (int*)malloc(sizeof(int) * 20);
if(q == nullptr)
{
return -1;
}
free(q);
int *q1 = new int[20]();
delete[]q1;
new还有很多种,我们常常用的就是抛出异常的new
int *p = new int(20);
不抛出异常的new
int *p2 = new (nothrow) int;
在对上生成常量的new
const int *p3 = new const int(40);



