在軟件開發過程中,常常需要動態地分配和撤銷內存空間,例如對動態鏈表中結點的插入與刪除。在C語言中是利用庫函數malloc和free來分配和撤銷內存空間的。C++提供了較簡便而功能較強的運算符new和delete來取代malloc和free函數。
雖然爲了與C語言兼容,C++仍保留malloc和free函數,但建議用戶不用malloc和free函數,而用new和delete運算符。
語法對比如下:
//分配基礎類型
int *p = (int *)malloc(sizeof(int));
*p = 10;
free(p);
int *p2 = new int;
*p2 = 10;
delete p2;
//分配數組變量
int *p3 = (int *)malloc(sizeof(int) * 10);
p3[0] = 1;
free(p3);
int *parray = new int[10];
parray[1] = 2;
delete [] parray;
char *pArray2 = new char[25]; //char buf[25]
delete[] pArray2;
//分配對象new delete
//相同 和 不同的地方 new能執行類型構造函數 delete操作符 能執行類的析構函數
class Test
{
public:
Test(int _a)
{
a = _a;
cout << "構造函數執行" << endl;
}
~Test()
{
cout << "析構函數執行" << endl;
}
protected:
private:
int a;
};
void main()
{
//c
Test *pT1 = (Test *)malloc(sizeof(Test));
free(pT1);
//c++
Test *pT2 = new Test(10);
delete pT2;
cout << "hello..." << endl;
system("pause");
}
兩者的不同:
- new能執行類的構造函數 malloc不行
- delete能執行類的析構函數 free不行
- free可以銷燬基礎類型 、分配數組類型但是不能銷燬類