上一篇文章學習了free,那么問題來了,c++里面的new/delete似乎也是這個功能啊,所以區別是什么呢?
于是在stackoverflow上搜了一下:
malloc/free & new/delete的區別
搬運工來了。。:
- new/delete
Allocate/release memory
1,Memory allocated from 'Free Store'
2,Returns a fully typed pointer.
3,new (standard version) never returns a NULL (will throw on failure)
4,Are called with Type-ID (compiler calculates the size)
5,Has a version explicitly to handle arrays.
6,Reallocating (to get more space) not handled intuitively (because of copy constructor).
7,Whether they call malloc/free is implementation defined.
8,Can add a new memory allocator to deal with low memory (set_new_handler)
9,operator new/delete can be overridden legally
10,constructor/destructor used to initialize/destroy the object
- 分配/釋放內存
1,從free空間分配內存
2,返回一個完全類型的指針(因為你要指明是什么類型的)
3,new如果分配失敗的話絕不會返回一個空指針NULL,而是會拋出失敗異常
4,用類型來申請就可以了(編譯器自動計算大小),(注:比如auto p=new int;
)
5,對處理數組有一個顯示的版本(可能是在分配一個數組的時候會特別的處理)
6,(不確定是否準確)會重新分配來獲取更大的空間而不是由于拷貝構造函數而直接處理(意會。。)
7,實現(new/delete)的時候就決定了是否會調用malloc/free函數
8,可以新增一個內存分配器來處理低可用內存(set_new_handler
)
9,操作符new/delete可以被合法的覆蓋
10,調用(這個類型的)構造函數和析構函數來初始化/刪除對象
(也就是說new/delete的是針對對象的!這個對象可以說int,double等,也可以是自定義的class)
malloc/free
Allocates/release memory
1,Memory allocated from 'Heap'
2,Returns a void*
3,Returns NULL on failure
4,Must specify the size required in bytes.
5,Allocating array requires manual calculation of space.
6,Reallocating larger chunk of memory simple (No copy constructor to worry about)
7,They will NOT call new/delete.
8,No way to splice user code into the allocation sequence to help with low memory.
9,malloc/free can NOT be overridden legally
- 1,內存來源于堆
2,返回的是void*
類型的指針
3,如果分配失敗的話,會返回一個NULL指針(所以我們在程序里面通過判斷是否為空檢測是否分配成功)
4,必須要指明需要多少Byte的空間!
5,分配數組需要人工計算需要多大空間
6,重新分配更大的內存,不需要考慮拷貝構造函數
7,這組函數不會調用new/delete
8,用戶代碼無法幫助解決低內存的問題
9,mallco/free不會被合法的覆蓋(無視?取消?)掉
繼續補充在網上看到的:
malloc與free是C++/C 語言的標準庫函數,new/delete 是C++的運算符。對于非內部數據類的對象而言,光用maloc/free 無法滿足動態對象的要求。對象在創建的同時要自動執行構造函數, 對象消亡之前要自動執行析構函數。由于malloc/free 是庫函數而不是運算符,不在編譯器控制權限之內,不能夠把執行構造函數和析構函數的任務強加malloc/free。
這個很重要,new的是對象!