1, New/delete is the operator of C + +, and Malloc/free is a function in C.
2, new do two things, one is to allocate memory, and the other is to call the class constructor; Similarly, delete invokes the destructor of the class and frees memory. malloc and free simply allocate and release memory.
3, new is an object, and malloc allocates a piece of memory, the new object can be accessed with a member function, do not directly access its address space; malloc allocates a memory area, which is accessed by a pointer, and the pointer to the new one is the type information. , and malloc returns a void pointer.
4, New/delete is reserved word, do not need the header file support; Malloc/free requires a header file library function support.
Let's take a look at how Malloc/free and new/delete implement dynamic memory management for objects, see example.
classobj{ Public: Obj () {cout<<"initialization"<<Endl;} ~obj () {cout <<"Destroy"<<Endl;} voidInitialize () {cout <<"initialization"<<Endl;} voidDestroy () {cout <<"Destroy"<<Endl;}};voidUsemallocfree () {OBJ*a = (obj*) malloc (sizeof(obj)); A-intialize (); // ...A->Destroy (); Free (a);}voidUsenewdelete () {OBJ*a =NewOBJ; //...delete A;}
The function of the class obj initialize simulates the function of the constructor, and the function destroy simulates the function of the destructor. In function Usemallocfree, because Malloc/free cannot execute constructors and destructors, member functions initialize and destroy must be called to complete initialization and cleanup work. The function usenewdelete is much simpler.
This is just an example, and no one will use Malloc/free to create class objects. In addition, new and delete supporting use, new[] and delete[] supporting use.
The difference between New/delete and Malloc/free in C + +