C + + 's new and delete operators

Source: Internet
Author: User

The functions of dynamically allocating and freeing memory in C are malloc calloc and free, while in C + + the new new[] Delete delete[] is used to request dynamic space and free space.

Note: new, new[], delete, and delete[] are operators, not functions; New and delete are also keywords for C + +.

The operator new is used to dynamically allocate a single space , while new[] is used to dynamically allocate an array, the operator delete is used to release the space allocated by new, and delete[] is used to release an array of new[] allocations.

The following is a simple example code

using namespacestd;intMain () {int*p =New int(5); int*q =New int[Ten]; *q = the; Q++; *q =293; cout<< *q <<Endl; cout<< *p <<Endl; Deletep; return 0;}

Run results

293 5

To avoid memory leaks, normally the new and delete, new[], and delete[] operators should appear paired, and do not mix these operators with the C language's dynamically allocated memory and several functions that release memory. It is recommended that you use the new, new[], delete, and delete[] operators for dynamic memory allocation and deallocation when writing C + + programs, rather than using memory allocation and deallocation functions in C, because new, new[], delete, and delete[] Operators can use some features of C + +, such as the constructors and destructors of classes, to better manage the memory of C + + programs.

C + + 's new and delete operators

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.