1、malloc與free是C/C++的標準庫函數,new/delete是C++的運算符。它們都可用於申請動態內存和釋放內存。
2、new/delete是運算符用於對象內存申請和釋放,當對象構造和析構的釋放調用new/delete。
3、malloc/free是庫函數,不在編譯的控制範圍內。不能把對象的構造和析構強加於malloc/free上。
看如下例子:
#include <iostream>
using namespace std;
class Obj
{
public:
Obj(void)
{
cout << "Obj Initialization." << endl;
}
~Obj(void)
{
cout << "Obj Destroy." << endl;
}
};
void UseMallocFree(void)
{
cout << "in UseMallocFree()" << endl;
Obj *a = (Obj*)malloc(sizeof(Obj));
free(a);
}
void UseNewDelete(void)
{
cout << "in UseNewDelete()" << endl;
Obj *a = new Obj;
delete a;
}
int main()
{
UseMallocFree();
cout << "\n\n\n" << endl;
UseNewDelete();
return 0;
}
執行結果:
由此可見,對象用malloc/free去申請內存根本不會調用構造和析構函數。因此對對象內部使用new/delete比較合適。