[Programming] Introduction to C++: What is the difference and connection between new and malloc?

Introduction to C++: What is the difference and connection between new and malloc?

What malloc/free and new/delete have in common is:

They all apply for space from the heap and need to be released manually by the user.

The difference between malloc/free and new/delete is:

  1. malloc and free are functions (header files are required); new and delete are operators
  2. The space requested by malloc will not be initialized; new can be initialized
  3. When malloc applies for space, you need to manually calculate the size of the space and pass it; new only needs to be followed by the type of space
  4. The return value of malloc is void*, which must be forced when used; new is not required, because new is followed by the type of space
  5. When malloc fails to apply for space, it returns NULL, so it must be null when used; new does not need, but new needs to catch exceptions
  6. When applying for a custom type object, malloc/free will only open up space and will not call the constructor and destructor; while new will call the constructor to complete the initialization of the object after applying for the space (or use the default value when the member variable is declared) ), delete will call the destructor to complete the cleanup of resources in the space before releasing the space

Note: The constructor with parameters cannot be used to apply and initialize multiple spaces with new
as follows:

Date* ptr=new Date[10]

Open up a continuous space to store 10 Date class objects, but if the Date class does not have a default constructor, the compiler will report an error. New a continuous space does not support initialization, so to create an object can only call the no-argument constructor or the full default constructor.

Guess you like

Origin blog.csdn.net/m0_46613023/article/details/114786425