new / delete和malloc / free有什么区别?

new / deletemalloc / free什么区别?

相关(重复?):我在哪些情况下使用malloc vs new?


新/删除

  • 分配/释放内存
  • 从“Free Store”分配的内存
  • 返回一个完全类型的指针。
  • 新(标准版)从不返回NULL(将失败)
  • 用Type-ID调用(编译器计算大小)
  • 有明确的版本来处理数组。
  • 重新分配(以获得更多空间)不直观地处理(因为复制构造函数)。
  • 他们是否调用malloc / free是实现定义的。
  • 可以添加一个新的内存分配器来处理低内存(set_new_handler)
  • 运算符new / delete可以合法地覆盖
  • 用于初始化/销毁对象的构造函数/析构函数
  • 的malloc /免费

  • 分配/释放内存
  • 从'堆'分配的内存
  • 返回一个void *
  • 失败时返回NULL
  • 必须以字节指定所需的大小。
  • 分配数组需要手动计算空间。
  • 重新分配更大块的内存很简单(不需要复制构造函数)
  • 他们不会调用新的/删除
  • 没有办法将用户代码拼接到分配序列中以帮助减少内存。
  • malloc / free不能被合法覆盖
  • 表格比较的功能:

     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分配的内存来自'Free Store',而由malloc分配的内存来自'Heap'。 这两个领域是否相同是一个实现细节,这是malloc和new不能混合的另一个原因。


    最相关的区别是new操作符分配内存然后调用构造函数,并delete调用析构函数然后释放内存。


    new呼叫对象的Ctor, delete呼叫Dtor。

    mallocfree只是分配和释放原始内存。

    链接地址: http://www.djcxy.com/p/239.html

    上一篇: What is the difference between new/delete and malloc/free?

    下一篇: Read/convert an InputStream to a String