新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C++中new和delete的介紹
介紹
成都創(chuàng)新互聯(lián)成立與2013年,先為黎川等服務(wù)建站,黎川等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為黎川企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
1.malloc,free和new,delete區(qū)別。
- a.malloc,free是C/C++的標(biāo)準(zhǔn)庫函數(shù)。new,delete是c++的操作符。
- b.malloc申請(qǐng)的是內(nèi)存,嚴(yán)格意義不是“對(duì)象”,new申請(qǐng)的可以理解為“對(duì)象”,new 時(shí)會(huì)調(diào)用構(gòu)造函數(shù),返回指向該對(duì)象的指針。
- c.對(duì)于class類型,必須用new/delete來創(chuàng)建和銷毀,自動(dòng)調(diào)用構(gòu)造和析構(gòu)函數(shù),malloc/free無法勝任。
2.使用new遵循原則:
- a.用new申請(qǐng)的內(nèi)存,必須用delete釋放。
- b.用new[]申請(qǐng)的內(nèi)存,必須用delete[]釋放。
- c.delete釋放內(nèi)存后,指針值不變,良好的風(fēng)格是釋放后指針置為NULL,如,delete p; p = NULL。
使用
1.申請(qǐng)一個(gè)對(duì)象
int* p1 = new int; delete p1; p1 = NULL;
2.申請(qǐng)多個(gè)對(duì)象
int* p1 = new int[12]; delete[] p1; p1 = NULL;
3.申請(qǐng)一個(gè)長度為1024的char數(shù)組
char* pArray = new char[1024]; for (int i=0; i < 1024; i++) { pArray[i] = i; } delete[] pArray; pArray = NULL;
4.申請(qǐng)一個(gè)類對(duì)象
#includeclass Student { public: char name[32]; int age; }; int main() { Student* pStu = new Student(); delete pStu; pStu = NULL; return 1; }
5.申請(qǐng)1024個(gè)類對(duì)象
#includeclass Student { public: int age; Student() { ... } ~Student() { ... } }; int main() { Student* pStu = new Student[1024]; for (int i=0; i<1024; i++) { pStu[i].age = i+1; } delete[] pStu; pStu = NULL; return 1; }
new多個(gè)對(duì)象不能傳參數(shù),要求該類必須有默認(rèn)構(gòu)造函數(shù)。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)創(chuàng)新互聯(lián)的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
文章標(biāo)題:C++中new和delete的介紹
當(dāng)前URL:http://www.ef60e0e.cn/article/gspjsc.html