The differences between new(delete) and malloc(free) in c/c++

这篇文章主要参考了quora和stackoverflow上的回答,这个问题本身并不是什么有难度的问题,所有的参考链接见文末

1. 'new' is only available in C++.  malloc() is available in both C and C++

    new只能在C++里使用,malloc可以在C或C++里使用

2. new is type-safe, malloc returns objects of type void*

    new是类型安全的,而malloc返回void*类型,需要手动转换成指定指针类型

3. new is an operator and can be overloaded, malloc is a function and cannot be overloaded

    new是一个运算符,因此它可以被重载。malloc是一个函数,不能被重载

4. Memory allocated via 'new' is not relocatable. In other words, there is no realloc() equivalent

    new分配的内存不能被重新转移并分配,换句话说,new没有类似realloc()的功能

5. new invokes the object's constructor and the corresponding call to delete invokes the object's destructor.

    new调用了对象的构造函数并且delete调用了析构函数

6. new throws an exception if there is not enough memory, malloc returns a NULL。

    当分配不成功的时候,new会抛出一个异常,而malloc会返回NULL值

7. The system may implement 'new' and malloc() using different heaps. New Memory allocated from 'Free Store' and malloc allocate memory from HEAP

    new和malloc有可能会用到不同的堆。

8. new has a version explicitly to handle arrays.

    new有一种明确的方法来处理数组的内存分配,即new[]

9. new can add a new memory allocator to deal with low memory (set_new_handler).

    new可以设置自己的内存分配器

 

references:

quora:

What are the differences between new/delete and malloc/free when allocating memory for objects?
stackoverflow:
What is the difference between new/delete and malloc/free?

posted on 2015-10-13 13:58  daghlny  阅读(228)  评论(0编辑  收藏  举报

导航