new / delete和malloc / free有什么区别?
new
/ delete
和malloc
/ free
什么区别?
相关(重复?):我在哪些情况下使用malloc vs new?
新/删除
的malloc /免费
表格比较的功能:
Feature | new/delete | malloc/free
--------------------------+--------------------------------+-------------------------------
Memory allocated from | 'Free Store' | 'Heap'
Returns | Fully typed pointer | void*
On failure | Throws (never returns NULL) | Returns NULL
Required size | Calculated by compiler | Must be specified in bytes
Handling arrays | Has an explicit version | Requires manual calculations
Reallocating | Not handled intuitively | Simple (no copy constructor)
Call of reverse | Implementation defined | No
Low memory cases | Can add a new memory allocator | Not handled by user code
Overridable | Yes | No
Use of (con-)/destructor | Yes | No
技术上来说,由new分配的内存来自'Free Store',而由malloc分配的内存来自'Heap'。 这两个领域是否相同是一个实现细节,这是malloc和new不能混合的另一个原因。
最相关的区别是new
操作符分配内存然后调用构造函数,并delete
调用析构函数然后释放内存。
new
呼叫对象的Ctor, delete
呼叫Dtor。
malloc
& free
只是分配和释放原始内存。
上一篇: What is the difference between new/delete and malloc/free?