C++動態配置記憶體後 delete 和delete [] 的真正區別
C++動態配置記憶體後 delete 和delete [] 的真正區別
資料來源:https://mp.weixin.qq.com/s?__biz=MzA3MTU1MzMzNQ==&mid=2247486573&idx=1&sn=6b96bbad6718f3d2e457086a8209cd82&chksm=9f2a9435a85d1d239cda4ba45fe6660ba40b50deadd340416d2be79d1b11813686923790bc9f&scene=126&sessionid=1598840115&key=baed9475c9f7eb8bca04091acfec4a542800dc4d4bea6d41bec22907002a9413fe200482ea8b0e0761be11c9c8b9eb5895d800ba89cf1b1cba14c8f19812a9da09a3c63f11b21d9f16a4d1dd3007604c7d02dd1f6a743d1c981944cfdf4febe38fe93fd9cb77ed0249ba5d84e6d7cbb6abaf1e8655b052c0595c0df4bc432abf&ascene=1&uin=MjIwODk2NDgxNw%3D%3D&devicetype=Windows+10+x64&version=62090529&lang=zh_TW&exportkey=ApGVhw0n6DahgiQhJD0r%2B2k%3D&pass_ticket=HWH0ihBWA2sCHd8WHMJN93RqHaWxZZ8W9JwPA6FItqxvyh%2BDmBkh5j9TDdMo8G6c
用法說明:
delete 釋放new分配的單個對象指針(指標)指向的內存
delete[] 釋放new分配的對像數組指針(指標)指向的內存
1. 針對簡單類型使用new分配後的不管是數組還是非數組形式內存空間用兩種方式均可如:
int *a = new int[10]; ... delete a; delete[] a;
2. 針對類Class,兩種方式體現出具體差異
class A { private: char *m_cBuffer; int m_nLen; `` public: A(){ m_cBuffer = new char[m_nLen]; } ~A() { delete [] m_cBuffer; } }; A *a = new A[10]; delete a; //仅释放了a指针指向的全部内存空间 但是只调用了a[0]对象的析构函数 剩下的从a[1]到a[9]这9个用户自行分配的m_cBuffer对应内存空间将不能释放 从而造成内存泄漏 delete[] a; //调用使用类对象的析构函数释放用户自己分配内存空间并且 释放了a指针指向的全部内存空间
One thought on “C++動態配置記憶體後 delete 和delete [] 的真正區別”
看完這篇你還能不懂C/C++ 語言 內存(記憶體)管理?
https://mp.weixin.qq.com/s/WvAsjLhgGlRJsxFPLAI3lw