The difference between C++ new/delete and malloc/free

The difference between new/delete and malloc/free

What new/delete and malloc/free have in common is that they both apply for space from the heap and need to be released manually by the user. The differences are:

  1. malloc and free are functions, new and delete are operators.
  2. The space requested by malloc will not be initialized, but new can be initialized.
  3. When malloc applies for space, you need to manually calculate the size of the space to be applied for and pass it. New only needs to follow the type of space.
  4. The return value of malloc is void *, which must be forced to the desired type when used. New is not needed, 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 to be used, but new needs to catch exceptions, because the bottom layer of new will throw an exception if the application fails.
  6. When applying for a custom type object, malloc/free will only open up/release space, and will not call the constructor and destructor. New will call the constructor to complete the initialization of the object after applying for space, and delete will call analysis before releasing the space. The constructor completes the cleanup of resources in the space.

Guess you like

Origin blog.csdn.net/qq_43579888/article/details/110505443