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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/240212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:59:56  来源:igfitidea点击:

What is the difference between new/delete and malloc/free?

c++memory-management

提问by MrDatabase

What is the difference between new/deleteand malloc/free?

new/deletemalloc/ 有free什么区别?

Related (duplicate?): In what cases do I use malloc vs new?

相关(重复?):在什么情况下我使用 malloc 还是 new?

回答by Martin York

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. Whether 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
  • 分配/释放内存
    1. 从“免费存储”分配的内存
    2. 返回一个完全类型的指针。
    3. new(标准版本)从不返回 NULL(失败时会抛出)
    4. 用 Type-ID 调用(编译器计算大小)
    5. 有一个显式处理数组的版本。
    6. 重新分配(以获得更多空间)未直观处理(由于复制构造函数)。
    7. 它们是否调用 malloc/free 是实现定义的。
    8. 可以添加新的内存分配器来处理低内存(set_new_handler)
    9. operator new/delete 可以被合法地覆盖
    10. 用于初始化/销毁对象的构造函数/析构函数

malloc/free

malloc/免费

  • 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 NOTcall new/delete
    8. No way to splice user code into the allocation sequence to help with low memory.
    9. malloc/free can NOTbe overridden legally
  • 分配/释放内存
    1. 从“堆”分配的内存
    2. 返回一个空*
    3. 失败时返回 NULL
    4. 必须以字节为单位指定所需的大小。
    5. 分配数组需要手动计算空间。
    6. 重新分配更大的内存块很简单(无需担心复制构造函数)
    7. 他们不会调用新的/删除
    8. 无法将用户代码拼接到分配序列中以帮助减少内存。
    9. 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 detail, which is another reason that malloc and new can not be mixed.

从技术上讲,new 分配的内存来自“自由存储”,而 malloc 分配的内存来自“堆”。这两个区域是否相同是一个实现细节,这也是malloc和new不能混用的另一个原因。

回答by Trap

The most relevant difference is that the newoperator allocates memory then calls the constructor, and deletecalls the destructor then deallocates the memory.

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

回答by James Curran

newcalls the ctor of the object, deletecall the dtor.

new调用对象的ctor,delete调用dtor。

malloc& freejust allocate and release raw memory.

malloc&free只分配和释放原始内存。

回答by Treb

new/deleteis C++, malloc/freecomes from good old C.

new/delete是 C++,malloc/free来自古老的 C。

In C++, newcalls an objects constructor and deletecalls the destructor.

在 C++ 中,new调用对象构造函数并delete调用析构函数。

mallocand free, coming from the dark ages before OO, only allocate and free the memory, without executing any code of the object.

malloc而且free,来自OO之前的黑暗时代,只分配和释放内存,不执行对象的任何代码。

回答by Encryptic

In C++ new/deletecall the Constructor/Destructor accordingly.

在 C++ 中new/ 相应地delete调用构造函数/析构函数。

malloc/freesimply allocate memory from the heap. new/deleteallocate memory as well.

malloc/free简单地从堆分配内存。new/ 也delete分配内存。

回答by Steve Jessop

The only similarities are that malloc/newboth return a pointer which addresses some memory on the heap, and they both guarantee that once such a block of memory has been returned, it won't be returned again unless you free/delete it first. That is, they both "allocate" memory.

唯一的相似之处是malloc/new都返回一个指向堆上某些内存的指针,并且它们都保证一旦返回了这样的内存块,除非您先释放/删除它,否则不会再次返回它。也就是说,它们都“分配”了内存。

However, new/deleteperform arbitrary other work in addition, via constructors, destructors and operator overloading. malloc/freeonly ever allocate and free memory.

但是,new/ 还delete可以通过构造函数、析构函数和运算符重载执行任意其他工作。malloc/free只分配和释放内存。

In fact, newis sufficiently customisable that it doesn't necessarily return memory from the heap, or even allocate memory at all. However the default newdoes.

事实上,它new是足够可定制的,它不一定从堆中返回内存,甚至根本不需要分配内存。但是默认情况下new

回答by Walter

The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor.

new 和 malloc 的主要区别在于 new 调用对象的构造函数,而对应的 delete 调用调用对象的析构函数。

There are other differences:

还有其他区别:

  • newis type-safe, mallocreturns objects of type void*

  • newthrows an exception on error, mallocreturns NULLand sets errno

  • newis an operator and can be overloaded, mallocis a function and cannot be overloaded

  • new[], which allocates arrays, is more intuitive and type-safe than malloc

  • malloc-derived allocations can be resized via realloc, new-derived allocations cannot be resized

  • malloccan allocate an N-byte chunk of memory, newmust be asked to allocate an array of, say, chartypes

  • new是类型安全的,malloc返回类型的对象void*

  • new出错时抛出异常,malloc返回NULL并设置 errno

  • new是一个运算符,可以重载,malloc是一个函数,不能重载

  • new[],它分配数组,比 malloc

  • malloc- 派生分配可以通过调整大小realloc,-new派生分配不能调整大小

  • malloc可以分配 N 字节的内存块,new必须要求分配一个数组,比如,char类型

Looking at the differences, a summary is malloc is C-esque, new is C++-esque. Use the one that feels right for your code base.

看区别,总结就是 malloc 是 C-esque,new 是 C++-esque。使用适合您的代码库的那个。

Although it is legal for new and malloc to be implemented using different memory allocation algorithms, on most systems new is internally implemented using malloc, yielding no system-level difference.

尽管使用不同的内存分配算法实现 new 和 malloc 是合法的,但在大多数系统上 new 是使用 malloc 内部实现的,不会产生系统级差异。

回答by herohuyongtao

There are a few things which newdoes that mallocdoesn't:

有一些事情newmalloc会这样做:

  1. newconstructs the object by calling the constructor of that object
  2. newdoesn't require typecasting of allocated memory.
  3. It doesn't require an amount of memory to be allocated, rather it requires a number of objects to be constructed.
  1. new通过调用该对象的构造函数来构造该对象
  2. new不需要对分配的内存进行类型转换。
  3. 它不需要分配大量内存,而是需要构造多个对象。

So, if you use malloc, then you need to do above things explicitly, which is not always practical. Additionally, newcan be overloaded but malloccan't be.

所以,如果你使用malloc,那么你需要明确地做上面的事情,这并不总是实用的。此外,new可以重载但malloc不能重载。

In a word, if you use C++, try to use newas much as possible.

总之,如果你用C++,尽量new多用。

回答by DanJ

also,

还,

the global new and delete can be overridden, malloc/free cannot.

全局 new 和 delete 可以被覆盖,malloc/free 不能。

further more new and delete can be overridden per type.

每种类型可以覆盖更多的 new 和 delete。

回答by Jorge Córdoba

newand deleteare C++ primitiveswhich declare a new instance of a class or delete it (thus invoking the destructor of the class for the instance).

newdelete是 C++原语,它们声明类的新实例或删除它(从而为实例调用类的析构函数)。

mallocand freeare C functionsand they allocate and free memory blocks (in size).

mallocfree是 C函数,它们分配和释放内存块(按大小)。

Both use the heap to make the allocation. mallocand freeare nonetheless more "low level" as they just reserve a chunk of memory space which will probably be associated with a pointer. No structures are created around that memory (unless you consider a C array to be a structure).

两者都使用堆进行分配。malloc并且free仍然更“低级”,因为它们只是保留了一块可能与指针相关联的内存空间。没有围绕该内存创建结构(除非您将 C 数组视为结构)。