# Include <iostream>;
# Include "xercesc/DOM. HPP"
Int main (){
Char * Pc = 0;
Char * PC2;
Int I = 21;
PC = new char;
STD: cout <(long) Pc <STD: Endl;
Delete PC;
STD: cout <(long) Pc <STD: Endl;
PC2 = new char;
STD: cout <(long) PC2 <STD: Endl;
Return 0;
}
Output:
[Root @ ts XML] #./A. Out
134519536
134519536
134519536
The address is not changed. Delete [] and delete are all the same.
--------------------------------------------------------------------------------
WhyglinuxReply: 12:08:12
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 [].
This question raised by the landlord is very good. 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), the program provided above proves that Delete [] is equivalent to delete. But for (2), the situation changes. See the following program.
# 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 // 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.
ShiyigsfReply: 17:53:54
Agree with whyglinux. The following is my test code:
Test environment: Win2000 professional, vc6.0
# Include <iostream. h>;
Void main ()
{
Char * P = new char [4];
Char * t;
Cout <(long) * P <(long) (* (p + 1) <Endl;
T = P;
Cout <(long) (* (t + 1) <Endl;
Delete [] P; // or delete P;
Cout <(long) (* (t + 1) <Endl;
}
But the results are the same, as shown below:
-51-51
-51
-35
It indicates that calling Delete [] and delete in a non-custom type has the same effect.
I don't know, right? Please advise!
Whyglinux replied to: 21:57:07
Judging whether the allocated memory is recycled cannot be seen from the changes in the memory value. The test above does not explain the problem.