What is the difference between "new" and "malloc" and "calloc" in C++?
What is the difference between "new" and "malloc" and "calloc" and others in family?
(When) Do I need anything other than "new" ?
Is one of them implemented using any other?
new and delete are C++ specific features. They didn't exist in C. malloc is the old school C way to do things. Most of the time, you won't need to use it in C++.
malloc allocates uninitialized memory. The allocated memory has to be released with free . calloc is like malloc but initializes the allocated memory with a constant (0). It needs to be freed with free . new initializes the allocated memory by calling the constructor (if it's an object). Memory allocated with new should be released with delete (which in turn calls the destructor). It does not need you to manually specify the size you need and cast it to the appropriate type. Thus, it's more modern and less prone to errors. new/delete + new[]/delete[]:
malloc/free + family:
Also see my related answer here
As other posts have pointed out: malloc/free is part of C++ to be compatible with C.
Also see: Stroustrup: new vs malloc
链接地址: http://www.djcxy.com/p/78536.html