Differences between delete and delete [] in C ++, and between delete
I have been not familiar with the differences between delete and delete [] in C ++. Today I encountered it. I checked it online and reached a conclusion. Make a backup to avoid loss.
C ++ tells us to use delete to reclaim the memory space of a single object allocated with new, delete [] is used to reclaim the memory space of a group of objects allocated with new []. New [] and delete [] are divided into two types: (1) Allocating and reclaiming space for basic data types; (2) Allocating and reclaiming space for custom data types.
See the following program.
12345678910111213141516171819202122 |
#include <iostream>; using namespace std; class T { public : T() { cout << "constructor" << endl; } ~T() { cout << "destructor" << endl; } }; int main() { const int NUM = 3; T* p1 = new T[NUM]; cout << hex << p1 << endl; // delete[] p1; delete p1; T* p2 = new T[NUM]; cout << p2 << endl; delete [] p2; } |
You can run this program on your own and check the different results of delete p1 and delete [] p1. I will not paste the running results here.
From the running results, we can see that only the object p1 [0] calls the Destructor during the space reclaim process of delete p1, other objects, such as p1 [1] and p1 [2], do not call their own destructor. This is the crux of the problem. If delete [] is used, all objects will first call their own destructor before the space is reclaimed. There is no destructor for objects of the basic type. Therefore, you can use delete and delete [] to recycle the array space composed of the basic types. However, you can only use delete [] for arrays of class objects. For a single new object, only delete can be used, and delete [] cannot be used to recycle space. Therefore, a simple usage principle is that new corresponds to delete, new [], and delete.
In my understanding, when delete is used to release the memory space applied for with new int [], because it is a basic data type and does not have a destructor, delete and delete [] are used, both of them will release the applied memory space. If the data type is customized and there is a destructor, the space applied for with new [] must be released using delete, because when you delete [], the destructor of the object array will be called one by one, and then the space will be released. If delete is used, only the destructor of the first object will be called, if the destructor of the subsequent object is not called, is its space released ??