Regarding the differences between malloc and new in terms of their respective mechanisms of handling memory allocation? [duplicate]
What are the differences between malloc and new in terms of their respective mechanisms of handling memory allocation?
malloc
doesn't throwbad_alloc
exception asnew
does.- Because malloc doesn't throw exceptions, you have to check its result against
NULL
(or nullptr in c++11 and above), which isn't necessary withnew
. However,new
can be used in a way it won't throw expections, as when functionset_new_handler
is set
- Because malloc doesn't throw exceptions, you have to check its result against
malloc
andfree
do not call object constructors and destructors, since there is no objects inC
.- see this question and this post.
Well, malloc()
is a more low-level primitive. It just gives you a pointer to n bytes of heap memory. The C++ new
operator is more "intelligent" in that it "knows" about the type of the object(s) being allocated, and can do stuff like call constructors to make sure the newly allocated objects are all properly initialized.
Implementations of new
often end up calling malloc()
to get the raw memory, then do things on top of that memory to initalize the objecs(s) being constructed.
Do you mean how they are implemented?
They can be implemented as anything, just malloc
may not call new
, and all standard new
s must call the global operator new(void*)
. Often new
is even implemented as calling malloc
but there is no requirement on how that is implemented. There are even dozens of allocators out there, each with some strengths and some weeknesses.
Or do you mean how they differ on the language level?
new
throws (unless it is called withstd::nothrow
) on allocation error. new expressions (not the operator new) calls the ctor.malloc
returns0
on allocation failures.
If the call fails, new
will throw an exception whereas malloc
will return NULL
.
For malloc
, the caller has to specify the amount of memory to be allocated, while new
automatically determines it.
These differences are concerning allocation, there are tons of others - new will call constructor, new can be overloaded, new is an operator whereas malloc is a function...
精彩评论