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
What is the difference between new/delete and malloc/free?
提问by MrDatabase
What is the difference between new
/delete
and malloc
/free
?
new
/delete
和malloc
/ 有free
什么区别?
Related (duplicate?): In what cases do I use malloc vs new?
相关(重复?):在什么情况下我使用 malloc 还是 new?
回答by Martin York
new/delete
新建/删除
- Allocate/release memory
- Memory allocated from 'Free Store'
- Returns a fully typed pointer.
- new (standard version) never returns a NULL (will throw on failure)
- Are called with Type-ID (compiler calculates the size)
- Has a version explicitly to handle arrays.
- Reallocating (to get more space) not handled intuitively (because of copy constructor).
- Whether they call malloc/free is implementation defined.
- Can add a new memory allocator to deal with low memory (set_new_handler)
- operator new/delete can be overridden legally
- constructor/destructor used to initialize/destroy the object
- 分配/释放内存
- 从“免费存储”分配的内存
- 返回一个完全类型的指针。
- new(标准版本)从不返回 NULL(失败时会抛出)
- 用 Type-ID 调用(编译器计算大小)
- 有一个显式处理数组的版本。
- 重新分配(以获得更多空间)未直观处理(由于复制构造函数)。
- 它们是否调用 malloc/free 是实现定义的。
- 可以添加新的内存分配器来处理低内存(set_new_handler)
- operator new/delete 可以被合法地覆盖
- 用于初始化/销毁对象的构造函数/析构函数
malloc/free
malloc/免费
- Allocates/release memory
- Memory allocated from 'Heap'
- Returns a void*
- Returns NULL on failure
- Must specify the size required in bytes.
- Allocating array requires manual calculation of space.
- Reallocating larger chunk of memory simple (No copy constructor to worry about)
- They will NOTcall new/delete
- No way to splice user code into the allocation sequence to help with low memory.
- malloc/free can NOTbe overridden legally
- 分配/释放内存
- 从“堆”分配的内存
- 返回一个空*
- 失败时返回 NULL
- 必须以字节为单位指定所需的大小。
- 分配数组需要手动计算空间。
- 重新分配更大的内存块很简单(无需担心复制构造函数)
- 他们不会调用新的/删除
- 无法将用户代码拼接到分配序列中以帮助减少内存。
- 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 new
operator allocates memory then calls the constructor, and delete
calls the destructor then deallocates the memory.
最相关的区别是new
运算符分配内存然后调用构造函数,delete
调用析构函数然后释放内存。
回答by James Curran
new
calls the ctor of the object, delete
call the dtor.
new
调用对象的ctor,delete
调用dtor。
malloc
& free
just allocate and release raw memory.
malloc
&free
只分配和释放原始内存。
回答by Treb
new
/delete
is C++, malloc
/free
comes from good old C.
new
/delete
是 C++,malloc
/free
来自古老的 C。
In C++, new
calls an objects constructor and delete
calls the destructor.
在 C++ 中,new
调用对象构造函数并delete
调用析构函数。
malloc
and 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
/delete
call the Constructor/Destructor accordingly.
在 C++ 中new
/ 相应地delete
调用构造函数/析构函数。
malloc
/free
simply allocate memory from the heap. new
/delete
allocate memory as well.
malloc
/free
简单地从堆分配内存。new
/ 也delete
分配内存。
回答by Steve Jessop
The only similarities are that malloc
/new
both 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
/delete
perform arbitrary other work in addition, via constructors, destructors and operator overloading. malloc
/free
only ever allocate and free memory.
但是,new
/ 还delete
可以通过构造函数、析构函数和运算符重载执行任意其他工作。malloc
/free
只分配和释放内存。
In fact, new
is sufficiently customisable that it doesn't necessarily return memory from the heap, or even allocate memory at all. However the default new
does.
事实上,它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:
还有其他区别:
new
is type-safe,malloc
returns objects of typevoid*
new
throws an exception on error,malloc
returnsNULL
and sets errnonew
is an operator and can be overloaded,malloc
is a function and cannot be overloadednew[]
, which allocates arrays, is more intuitive and type-safe thanmalloc
malloc
-derived allocations can be resized viarealloc
,new
-derived allocations cannot be resizedmalloc
can allocate an N-byte chunk of memory,new
must be asked to allocate an array of, say,char
types
new
是类型安全的,malloc
返回类型的对象void*
new
出错时抛出异常,malloc
返回NULL
并设置 errnonew
是一个运算符,可以重载,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 new
does that malloc
doesn't:
有一些事情new
不malloc
会这样做:
new
constructs the object by calling the constructor of that objectnew
doesn't require typecasting of allocated memory.- It doesn't require an amount of memory to be allocated, rather it requires a number of objects to be constructed.
new
通过调用该对象的构造函数来构造该对象new
不需要对分配的内存进行类型转换。- 它不需要分配大量内存,而是需要构造多个对象。
So, if you use malloc
, then you need to do above things explicitly, which is not always practical. Additionally, new
can be overloaded but malloc
can't be.
所以,如果你使用malloc
,那么你需要明确地做上面的事情,这并不总是实用的。此外,new
可以重载但malloc
不能重载。
In a word, if you use C++, try to use new
as 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
new
and delete
are C++ primitiveswhich declare a new instance of a class or delete it (thus invoking the destructor of the class for the instance).
new
和delete
是 C++原语,它们声明类的新实例或删除它(从而为实例调用类的析构函数)。
malloc
and free
are C functionsand they allocate and free memory blocks (in size).
malloc
和free
是 C函数,它们分配和释放内存块(按大小)。
Both use the heap to make the allocation. malloc
and free
are 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 数组视为结构)。