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 [].
Many people have noticed this problem, but they do not know why.
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.
For (1), it has been proved that Delete [] is equivalent to delete. But for (2), the situation changes. See the following program.
# Include <iostream >;</P> <p> using namespace STD; </P> <p> class t {</P> <p> public: </P> <p> T () {cout <"constructor" <Endl ;}</P> <p> ~ T () {cout <"destructor" <Endl ;}</P> <p >}; </P> <p> int main () </P> <p >{</P> <p> const int num = 3; </P> <p> T * P1 = new T [num]; </P> <p> cout <pex <P1 <Endl; </P> <p> // Delete [] p1; </P> <p> Delete P1; </P> <p> T * P2 = new T [num]; </P> <p> cout <P2 <Endl; </P> <p> Delete [] P2; </P> <p >}< br/>
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.