1. When you use new, two things will happen. First, the memory is configured (through the operator new function ). Second, one or more constructors will be called for this memory. When you use Delete, there are also two things: one or more Destructors will be called for this memory, and then the memory will be released (through the operator delete function ).
2. If you use delete without parentheses, delete assumes that the deleted object is a single object. Otherwise, it is assumed that the object to be deleted is an array.
3. String * stringptr1 = new string;
String * stringptr2 = new string [100];
......
Delete stringptr1;
Delete [] stringptr2;
If you use the [] form to stringptr1, the result is undefined. If you do not use the [] format for stringptr2, the result is also undefined. The inner type such as Int Is also undefined, even if this type does not have Destructors.
4. therefore, the game rules are very simple. If you use [] when calling New, you also use [] when calling Delete. If you do not call New when [], then you should not use [] During the call.
Note: New and delete must appear in pairs; otherwise, memory leakage may occur.
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, let's take a look at 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 when Delete P1 recycles space, only the object P1 [0] calls the destructor, 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.
objects of the basic type have no destructor. Therefore, the delete and delete [] functions can be used to reclaim the array space composed of the basic types; however, for the array of class objects, only delete [] can be used. For a single new object, only delete can be used, and delete [] cannot be used to recycle space.
therefore, a simple principle is to use new and delete, new [], and delete.