本文介绍了new/delete 和 malloc/free 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
new/delete 和 malloc/free 有什么区别?
What is the difference between new/delete and malloc/free?
相关(重复?):在什么情况下我应该使用 malloc 还是 new?
推荐答案new/delete
- 分配/释放内存
new / delete
- Allocate / release memory
- 从免费存储"分配的内存.
- 返回一个完全类型的指针.
- new(标准版本)从不返回 NULL(失败时会抛出).
- 使用类型 ID 调用(编译器计算大小).
- 有一个明确处理数组的版本.
- 重新分配(以获得更多空间)未直观处理(因为复制构造函数).
- 是否调用 malloc/free 是实现定义的.
- 可以添加一个新的内存分配器来处理低内存(std::set_new_handler).
- operator new/operator delete 可以合法覆盖.
- 用于初始化/销毁对象的构造函数/析构函数.
- 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.
- 分配/释放内存
- Allocate / release memory
- 从堆"分配的内存.
- 返回一个 void*.
- 失败时返回 NULL.
- 必须以字节为单位指定所需的大小.
- 分配数组需要手动计算空间.
- 重新分配更大的内存块很简单(无需担心复制构造函数).
- 他们不会调用new/delete.
- 无法将用户代码拼接到分配序列中以帮助降低内存.
- malloc/free 可以不能被合法地覆盖.
- 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 NOT call new / delete.
- No way to splice user code into the allocation sequence to help with low memory.
- malloc / free can NOT be overridden legally.
内存分配自 | '免费商店' | '堆' |
退货 | 全类型指针 | void* |
失败时 | 抛出(从不返回NULL) | 返回NULL |
所需尺寸 | 编译器计算 | 必须以字节为单位指定 |
处理数组 | 有明确的版本 | 需要手动计算 |
重新分配 | 不直观 | 简单(无复制构造函数) |
反向调用 | 实现定义 | 没有 |
低内存情况 | 可以添加一个新的内存分配器 | 不被用户代码处理 |
可覆盖 | 是 | 没有 |
构造函数/析构函数的使用 | 是 | 没有 |
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不能混用的另一个原因.
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 cannot be mixed.
更多推荐
new/delete 和 malloc/free 有什么区别?
发布评论