1.malloc和free是庫函數;new和delete是C++的關鍵字
2.malloc是以字節來申請堆內存;new是以類型申請堆空間
3.malloc和free是單純的申請內存和釋放內存
4.new和delete分別負責申請內存調用calss的構造函數初始化和調用析構函數釋放資源
5.new申請的內存使用free釋放,是不會觸發調用析構函數的,一般會造成資源泄露
例子:
#include <new>
#include <cstdlib>
#include <iostream>
using namespace std;
class T {
public:
T(){cout<<"Call T()"<<endl;iv = 100;};
~T(){cout<<"Call ~T()"<<endl;}
int GetIv(){return iv;}
private:
int iv;
};
void func()
{
int *t1 = static_cast<int *>(malloc(sizeof(int)));
int *t2 = new int(10);//new 可以申請內存同時也可以賦值
*t1 = 88;//malloc則不行
cout << "begin :*t1"<<*t1<<",*t2="<<*t2<<endl;
free(t1);
delete t2;
cout << "end :t1"<<t1<<",t2="<<t2<<endl;
}
int main(void)
{
//func();
T *t1 = new T();//她會調用構造函數,以類型申請堆空間
T *t2 = static_cast<T *>(malloc(sizeof(T))); //不會調用構造和析構函數,以字節申請堆空間
cout<<"t1.iv = "<<t1->GetIv()<<endl;
delete t2;//觸發析構函數,析構函數用於釋放資源
cout<<"t2.iv = "<<t2->GetIv()<<endl;
free(t1);//如果new申請的空間,用free釋放,析構函數是不會調用,會造成資源泄露
return 0;
}
perryn@:/data/source/Cpp/demo:./a.out
Call T()
t1.iv = 100
t2.iv = 0
Call ~T()