Using malloc Versus new

南笙酒味 提交于 2019-12-11 08:25:55

问题


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

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


回答1:


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

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.

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

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



回答2:


You can find FAQ with your question here

And another good answer: In what cases do I use malloc vs new?



来源:https://stackoverflow.com/questions/4390356/using-malloc-versus-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!