1、malloc和free是C语言标准函数库中的两个函数,new/delete是C++语言中两个运算符。
2、malloc/free和new/delete都是用来申请动态内存的。
3、new 不止是分配内存,而且会调用类的构造函数,同理delete会调用类的析构函数,而malloc则只分配内存,不会进行初始化类成员的工作,同样free 也不会调用析构函数。
4、malloc得到的指针无类型,new出来的指针是带有类型信息的。
5、对于非内部数据类型的对象而言,光用maloc/free无法满足动态对象的要求。对象在创建的同时 要自动执行构造函数,对象在消亡之前要自动执行析构函数。由于malloc/free是库函数而不是运算符,不在编译器控制权限之内,不能够把执行构造函数和析构函数的任务强加于malloc/free。
6、如果用free释放“new创建的动态对象”,那么该对象因无法执行析构函数而可能导致程序出错。如 果用delete释放“malloc申请的动态内存”,理论上讲程序不会出错,但是该程序的可读性很差。所以new/delete 必须配对使用,malloc/free也一样。
7、实例如下:
#include <iostream>
#include<malloc.h>
using namespace std;
class Demo
{
public:
Demo();
~Demo();
void init();
void drop();
};
Demo::Demo()
{
cout<<"Demo is made"<<endl;
}
Demo::~Demo()
{
cout<<"Demo is drop"<<endl;
}
void Demo::init()
{
cout<<"Demo is made"<<endl;
}
void Demo::drop()
{
cout<<"Demo is drop"<<endl;
}
void usenew()
{
Demo *d = new Demo;
delete d;
}
void usemalloc()
{
Demo *d = (Demo*)malloc(sizeof(Demo));
d->init();
d->drop();
}
int main()
{
usenew();
usemalloc();
return 0;
}
结果如下:
Demo is made
Demo is drop
Demo is made
Demo is drop
8、如果用free释放“new创建的动态对象”,那么该对象因无法执行析构函数而可能导致程序出错。如 果用delete释放“malloc申请的动态内存”,理论上讲程序不会出错,但是该程序的可读性很差。所以new/delete 必须配对使用,malloc/free也一样。
转载于:https://blog.51cto.com/telesli1013/821302