C ++ new and delete operators Introduction

In the C language, with dynamic memory allocation function malloc (), with the release of the memory free () function. As follows:

. 1  int * P = ( int *) the malloc ( the sizeof ( int ) * 10 ); // allocate 10 int type memory 
2 Free (P); // release the memory

In C ++, these two functions can still be used, but C ++ has added two keywords, new and delete: new to dynamically allocate memory, delete to free memory.

Allocate memory using new and delete easier:

. 1  int * P = new new  int ; // allocate a memory space int type 
2 Delete P; // release the memory

new operator extrapolates the desired size of the space in accordance with the following data types.

If you want to assign a set of consecutive data, use new []:

. 1  int * P = new new  int [ 10 ]; // allocate 10 int type memory 
2 Delete [] P;

With new [] allocated memory need to use delete [] release, they are one to one.

And malloc (), like, new memory is allocated in the heap, you must manually release, or can only wait until the end of the recovery program run by the operating system. In order to avoid memory leaks, and generally Delete new, new [] and delete [] operator should appear in pairs, and not to the malloc C language (), Free () mixed together.

In C ++, it is recommended to use new and delete to manage memory, they can use some of the new features of C ++, the most obvious is that it automatically call the constructor and destructor.

Guess you like

Origin www.cnblogs.com/ybqjymy/p/12171429.html