对于一个指针可以多次使用delete_【C++札记】new和delete
生活随笔
收集整理的這篇文章主要介紹了
对于一个指针可以多次使用delete_【C++札记】new和delete
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
malloc,free和new,delete區別:
?a.malloc,free是C/C++的標準庫函數。new,delete是c++的操作符。
?b.malloc申請的是內存,嚴格意義不是“對象”,new申請的可以理解為“對象”,new 時會調用構造函數,返回指向該對象的指針。
?c.對于class類型,必須用new/delete來創建和銷毀,自動調用構造和析構函數,malloc/free無法勝任。
使用new遵循原則:
?a.用new申請的內存,必須用delete釋放。
?b.用new[]申請的內存,必須用delete[]釋放。
?c.delete釋放內存后,指針值不變,良好的風格是釋放后指針置為NULL,如,delete p;p = NULL。
使用
1.申請一個對象
int*?p1?=?new?int;delete?p1;
p1?=?NULL;
2.申請多個對象
int*?p1?=?new?int[12];delete[]?p1;
p1?=?NULL;
3.申請一個長度為1024的char數組
char*?pArray?=?new?char[1024];for?(int?i=0;?i?1024;?i++)
{
????pArray[i]?=?i;
}
delete[]?pArray;
pArray?=?NULL;
4.申請一個類對象
#include?class?Student
{
public:
????char?name[32];
????int??age;
};
int?main(){
????Student*?pStu?=?new?Student();
????delete?pStu;
????pStu?=?NULL;
????return?1;
}
5.申請1024個類對象
#include?class?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多個對象不能傳參數,要求該類必須有默認構造函數。
===推薦閱讀===
阿里巴巴 29 個屌炸天的開源項目16個超級實用的Java工具類?
[C++札記]內聯函數
技術群:>>后臺回復加群<<
喜歡就搓個"在看"↓↓總結
以上是生活随笔為你收集整理的对于一个指针可以多次使用delete_【C++札记】new和delete的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小米9私密相册怎么找_“拼藏搜”,手机相
- 下一篇: 代码 抠图_3 行 Python 代码