New and delete are the two operators that C + + uses to manage heap memory , corresponding to malloc and free in C, but malloc and free are functions, and new and delete are operators . Besides
New will also invoke the object's constructor while requesting memory, and malloc will only request memory;
Delete calls the object's destructor before releasing the memory, and free frees only the memory.
the internal implementation of the new operator is divided into two steps :
Memory allocation
Call the appropriate operator new(size_t) function to dynamically allocate memory. If operator new(size_t) memory cannot be obtained successfully, the calling new_handler() function is used to handle the new failure problem. Throws an exception if the function is not set new_handler() or if enough memory is not new_handler() allocated. std::bad_alloc The function called by the "new operator", in operator new(size_t) accordance with the name lookup rule of C + +, first makes a name lookup (that is, the ADL rule) that relies on the argument, the internal (member function) of the data type T where the memory is to be requested, the namespace at which the data type T is defined, and, if not, calls the global ::operator new(size_t)function.
constructor function
initializes an object (constructor) of the appropriate type on the dynamic block of memory allocated to it and returns its first address. If an exception is thrown when the constructor is called to initialize the object, the automatically called operator delete(void*, void*) function frees the memory already allocated to it.
The internal implementation of the delete operator is divided into two steps:
Destructors
Call the appropriate type of destructor to handle possible resource deallocation within the class.
Memory release
Call the appropriate operator delete(void *) function. The invocation order refers to the above operator new(size_t) function (ADL rule).
Class T{public: T () { cout << constructor. "<< Endl; } ~t () { cout << "destructor. "<< Endl; } void * operator new (size_t sz) { T * t = (t*) malloc (sizeof (t)); cout << "memory allocation. "<< Endl; return t; } void operator delete (void *p) {free (p); cout << "Memory free. "<< Endl; return;} }; int main () { T * t = new T (),//memory allocation, re-constructor delete T;//destructor, then memory release return 0;}
Attention:
Free can only release the underlying type of memory resources;
Delete on the basis of the free function, increased the processing of the class resource memory space.
C + + 's new and delete