In C + +, the new function allocates memory on the heap, which allocates memory dynamically, in three main forms:
1. Allocate a space uninitialized int* p=new int;
2. Assigning a space initialization int* p=new int (initial value)
3. Allocate a continuous space of int* p=new int[Memory]
It is also released manually after allocating memory on the heap, or a memory leak occurs. There are two forms of memory deallocation allocated on the heap in C + +:
Delete and delete [], how do you choose to use these two releases? What happens when you choose the wrong way?
Take an example to illustrate:
#include <iostream>using namespace Std;class a{public:a () {cout<< "A" <<ENDL;} ~a () {cout<< "~a" <<ENDL;} Private:};int Main (int argc, char const *argv[]) {A * p=new a[3];d elete[] p;//delete P;return 0;}
In this example, let's look at the results:
If you use detele[] p to release the memory of the new application, it can be released successfully:
650) this.width=650, "src=" Http://s3.51cto.com/wyfs02/M01/7C/BF/wKioL1bXqC3w_4LuAAAt-T8ypck917.png "title=" Capture 1 won. PNG "alt=" Wkiol1bxqc3w_4luaaat-t8ypck917.png "/>
and using delete p to release, there will be an error
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/7C/C1/wKiom1bXqA_iqkvcAAJDOzw9PQA749.png "title=" capture. PNG "alt=" Wkiom1bxqa_iqkvcaajdozw9pqa749.png "/>
and observe the error point can be found: delete p in the process of reclaiming space, only p[0] This object called the destructor, other objects such as p1[1], p1[2], etc. did not call their own destructor, so there is a problem.
A summary of the difference between delete and delete[] and when to use it is reviewed through data and experiments:
If you use delete[], all objects will first call their own destructors before reclaiming the space. Basic types of objects do not have destructors, so it should be possible to reclaim the array space of basic types with delete and delete[], but only with delete[] for an array of class objects. For a single object of new, you can only use Delete to reclaim space with delete[]. new allocates the memory space of a single object when using the delete, reclaim the memory space of a set of objects allocated by new[] with delete[]. New and delete, new[], and delete[] correspond to use.
This article is from the "June Feng Eureka" blog, please be sure to keep this source http://10274409.blog.51cto.com/10264409/1747048
Delete and delete[]