new/delete和malloc/free的区别是什么?
相关(重复?):在什么情况下我使用malloc vs new?
new/delete和malloc/free的区别是什么?
相关(重复?):在什么情况下我使用malloc vs new?
当前回答
唯一的相似之处是malloc/new都返回一个指向堆上一些内存的指针,而且它们都保证一旦这样的内存块被返回,它就不会再次返回,除非你先释放/删除它。也就是说,它们都“分配”内存。
然而,通过构造函数、析构函数和操作符重载,new/delete还执行其他任意工作。Malloc /free只分配和释放内存。
事实上,new具有足够的可定制性,它不必从堆中返回内存,甚至根本不必分配内存。但是默认的new可以。
其他回答
1.New syntex比malloc()简单
2.New /delete是一个运算符,其中malloc()/free() 是一个函数。
3.New /delete执行速度比malloc()/free()快,因为编译器直接粘贴了新的程序集代码。
4.我们可以通过操作符重叠来改变程序中的new/delete含义。
最相关的区别是,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 (std::set_new_handler). operator new / operator delete can be overridden legally. Constructor / destructor used to initialize / destroy the object.
Malloc / free
分配/释放内存 从“堆”分配内存。 返回一个void*。 失败时返回NULL。 必须以字节为单位指定所需的大小。 分配数组需要手动计算空间。 分配更大的内存块很简单(不需要担心复制构造函数)。 它们不会调用new / delete。 无法将用户代码拼接到分配序列中以帮助解决低内存问题。 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 constructor / destructor | Yes | No |
从技术上讲,由new分配的内存来自“Free Store”,而由malloc分配的内存来自“Heap”。这两个区域是否相同是一个实现细节,这是malloc和new不能混合使用的另一个原因。
此代码用于使用delete关键字或free函数。但是当创建一个 指针对象使用'malloc'或'new'释放对象内存使用 删除即使对象指针也可以调用类中的函数。后 使用free而不是delete,在free语句之后也可以, 但是当两者同时使用时,只有指针对象不能调用类中的函数。 代码如下:
#include<iostream>
using namespace std;
class ABC{
public: ABC(){
cout<<"Hello"<<endl;
}
void disp(){
cout<<"Hi\n";
}
};
int main(){
ABC* b=(ABC*)malloc(sizeof(ABC));
int* q = new int[20];
ABC *a=new ABC();
b->disp();
cout<<b<<endl;
free(b);
delete b;
//a=NULL;
b->disp();
ABC();
cout<<b;
return 0;
}
输出: 你好 嗨 0 x2abfef37cc20
要使用malloc(),我们需要包含<stdlib.h>或 <alloc.h>在程序中,这不是new. h所必需的。 New和delete可以重载,但malloc不能。 使用位置new,我们可以将地址传递到我们想要的位置 分配内存,但这在malloc的情况下是不可能的。