特性对比表:
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分配的内存来自“空闲存储”,而malloc分配的内存来自“堆”。 这两个区域是否相同是一个实现细节,这也是malloc和new不能混合的另一个原因。
最相关的区别是new
运算符分配内存然后调用构造函数,而delete
调用析构函数然后释放内存。
new
调用对象的ctor,delete
调用DTOR。
malloc
& free
只需分配和释放原始内存。