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 followingProgram.
# 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
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.