The difference between New/delete and Malloc/free in C + +

Source: Internet
Author: User

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 + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.