What is the difference between several alloc methods of memory in c++?
like so new, malloc and so on ...
thx
What is the difference between several alloc methods of memory in c++?
like so new, malloc and so on ...
thx
malloc allocates uninitialized memory. Malloc is not type safe
new initializes the allocated memory by calling the constructor. Also new keyword is type safe
delete is used to deallocate memory from the heap.
NOTE:- new
and delete
are C++ specific features.
Besides many other point which you may want to see. Here is one point which is worth reading
[16.4] Why should I use new instead of trustworthy old malloc()?
FAQ: new/delete call the constructor/destructor; new is type safe, malloc is not; new can be overridden by a class.
FQA: The virtues of new mentioned by the FAQ are not virtues, because constructors, destructors, and operator overloading are garbage (see what happens when you have no garbage collection?), and the type safety issue is really tiny here (normally you have to cast the void* returned by malloc to the right pointer type to assign it to a typed pointer variable, which may be annoying, but far from "unsafe").
Oh, and using trustworthy old malloc makes it possible to use the equally trustworthy & old realloc. Too bad we don't have a shiny new operator renew or something.
Still, new is not bad enough to justify a deviation from the common style used throughout a language, even when the language is C++. In particular, classes with non-trivial constructors will misbehave in fatal ways if you simply malloc the objects. So why not use new throughout the code? People rarely overload operator new, so it probably won't get in your way too much. And if they do overload new, you can always ask them to stop.