What is the difference between new/delete and malloc/free?
What is the difference between new
/ delete
and malloc
/ free
?
Related (duplicate?): In what cases do I use malloc vs new?
new/delete
malloc/free
Table comparison of the features:
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
Technically memory allocated by new comes from the 'Free Store' while memory allocated by malloc comes from the 'Heap'. Whether these two areas are the same is an implementation details, which is another reason that malloc and new can not be mixed.
最相关的区别是new
操作符分配内存然后调用构造函数,并delete
调用析构函数然后释放内存。
new
calls the ctor of the object, delete
call the dtor.
malloc
& free
just allocate and release raw memory.