C++ learning 7-new and delete

In C language, the functions for dynamically allocating and freeing memory are malloc, calloc and free, while in C++ language, new, new[], delete and delete[] operators are usually used to dynamically allocate and free memory .

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

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 allocated by new[].

"new data type" is the basic syntax of the new keyword, which can dynamically allocate a space of the size of a data type. For example:
int *p = new int;
allocates an int space for the p pointer. The new operator infers the required amount of space based on the type of data requested to be allocated.

new[] is to allocate space for an array. The specific syntax is as follows:
int *A = new int[10];
This statement allocates space for an array to the A pointer, and the array has 10 int array members. If the allocation is successful, the p pointer points to the first address,
and the array contains 10 The addresses of members are consecutive, and their addresses are A, A+1, A+2, ..., A+9.

The delete operator is specially used to release the dynamic storage space allocated by new. We allocated an int type space for p earlier. We can release it as follows:
    delete p;
    delete[] is used to release the space allocated by new The array space allocated by new[], we allocated ten int units for the A pointer earlier, forming an array, which can be released as follows:
    delete[] p;
    In order to avoid memory leaks, usually new and delete, new[] and delete[] operators should appear in pairs, and do not mix these operators with several functions that dynamically allocate and free memory in C language. It is recommended to use the new, new[], delete and delete[] operators for dynamic memory allocation and release as much as possible when writing C++ programs, instead of using the functions of memory allocation and release in C language, because new, new[], The delete and delete[] operators can use some features of C++, such as class constructors and destructors, to better manage the memory of C++ programs.
    
    The heap is a piece of memory maintained by the operating system, and free storage is the abstract concept of dynamically allocating and releasing objects through new and delete in C++. Heap and free memory are not equivalent.
    "In C++, the memory area is divided into 5 areas, namely heap, stack, free storage area, global/static storage area, and constant storage area".
    "The memory block allocated by malloc on the heap is released by free, while the memory applied by new is in the free storage area and released by delete."

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325114982&siteId=291194637