使用malloc与新 [英] Using malloc Versus new

查看:171
本文介绍了使用malloc与新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用 pointer = new type [size] 一段时间,刚刚发现 malloc

I've been using pointer = new type[size] for a while now and just recently discovered malloc.

malloc 之间是否有技术上的差异?如果是这样,使用一个的优势是什么?

Is there a technical difference between malloc and new? If so, what are the advantages to using one over the other?

推荐答案

malloc 是一个函数调用,在这种情况下是一个新的表达式。

malloc is a function call, new in this case an expression.

new 将分配内存并使用默认构造函数构造该数组的所有元素。 malloc 只是回传了大量未初始化的内存。

The difference is; new will allocate memory and construct all the elements of that array with the default constructor. malloc just gives back a chunk of uninitialized memory.

更进一步, :: operator新将抛出 std :: bad_alloc 或新的处理程序(如果有)。

Further still, ::operator new will throw std::bad_alloc or a new handler if one was registered.

标准库定义了一个新的,接受另一个参数 nothrow ,如果分配失败则返回一个0指针。

The standard library defines a new that accepts a further parameter nothrow which returns a 0 pointer if the allocation fails.

int *x = new(std::nothrow) int[20]; // include <new>, return 0 on failure

这篇关于使用malloc与新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆