1.malloc/free 是C/C++的标准库函数,new/delte是C++运算符。
2.对于非内部数据类型来说,例如对象在创建时需要调用构造函数,在消亡的时候需要调用析构函数,而malloc/free无发满足这个要求
3.malloc/free是库函数,不是运算符,不在编译器控制权限之内
例如一下代码:
#include<iostream>
using namespace std;
class Obj
{
public:
Obj(void)
{
cout << "Initialization" <<endl;
}
~Obj()
{
cout << "Destroy" << endl;
}
};
void UseMallocFree()
{
cout << "MallocFree()" << endl;
Obj *a = (Obj*)malloc(sizeof(Obj));
free(a);
}
void UseNewDelete()
{
cout << "UseNewDelete()" << endl;
Obj *a = new Obj;
delete a;
}
int main()
{
UseMallocFree();
UseNewDelete();
system("pause");
return 0;
}
运行结果:
MallocFree()
UseNewDelete()
Initialization
Destroy
在malloc的时候并未调用构造函数,故对非内部数据类型是用new/delete比较合适