• new/delete和malloc/free的区别






    转自: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.



  • 相关阅读:
    基于51单片机数码管显示经ADC0808转化1K电位器分压5V模拟量为数字量的项目工程
    基于51单片机数码管显示经ADC0808转化1K电位器分压5V模拟量为0V-5V数字量的项目工程
    浅谈移动端过长文本溢出显示省略号的实现方案
    浅谈自动化测试
    Tomcat 优雅关闭之路
    InnoDB 事务加锁分析
    Tomcat 9.0.26 高并发场景下DeadLock问题排查与修复
    Kotlin 协程真的比 Java 线程更高效吗?
    Spark 数据倾斜及其解决方案
    大数据平台架构设计探究
  • 原文地址:https://www.cnblogs.com/jubincn/p/3381197.html
Copyright © 2020-2023  润新知