new/delete和malloc/free的区别

来源:互联网 发布:串口奇偶校验算法 编辑:程序博客网 时间:2024/05/22 14:26





转自:http://stackoverflow.com/questions/240212/what-is-the-difference-between-new-delete-and-malloc-free

new/delete

  • 分配/释放内存
    1. 从'Free Store'中释放内存
    2. 返回值为带类型的指针.
    3. new (标准版本)在内存分配失败时会抛出一个failure,而不是返回NULL
    4. 参数为一个类的声明(编译器负责计算内存大小),而不是内存大小的数值
    5. 有专门来处理数组的语法
    6. 因为拷贝构造函数,不能自由地分配更大的空间.(这点不是很明白)
    7. new/delete是否调用malloc/free将取决于编译器.
    8. 可以添加一个新的内存分配器来处理内存不足的情况 (set_new_handler)
    9. new/delete是操作符,可以被重载
    10. 会调用构造函数/析构函数

malloc/free

  • 分配/释放内存
    1. 从堆中分配内存
    2. 返回值类型为void*
    3. 若失败,返回NULL
    4. 必须指定所分配的空间大小
    5. 分配数组时需要手动来计算数组大小
    6. 可以自由地分配更大的空间(不会有类似拷贝构造函数来影响)
    7. 他们不会调用new/delete
    8. 不能使用set_new_handler来处理内存过低的情况
    9. malloc/free是C函数,不能被重写

从技术上来讲,new是从"Free Store"中分配内存,而malloc从“堆”中分配内存。堆和“Free Store”是否是同一个区域将由具体的实现细节来决定,这也是malloc和new不能混用的另一个原因。


原文:

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. If 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

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

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.