When new is used (that is, an object is dynamically generated through new)
When delete is used, two events occur: one (or more) destructor is called for the memory, then the memory is released (through the function named operator delete ). The biggest problem with delete is: How many objects exist in the memory to be deleted? (The pointer to be deleted refers to a single object or an object array ?) The answer to this question determines how many destructor must be called.
The memory layout of a single object is different from the memory layout of an object array: the memory used by the array includes "array size" records, so that delete can determine the number of destructor to be called. The memory of a single object does not have this record.
Delete [] determines that the pointer points to an array and calls the Destructor multiple times. Therefore, remember to take the same form for new and delete.
Std: string * strPtr1 = new std: string; std: string * strPtr2 = new std: string [100];... delete strPtr1; // delete an object delete [] strPtr2; // delete an array composed of Objects
If you use the delete [] Form for strPtr1: delete reads some memory and interprets it as "array size", and then calls the Destructor multiple times.
If the delete [] form is not used for strPtr2: 99 destructor may not be called, and objects may not be deleted as appropriate.
That is to say, the above two situations may lead to uncertain behaviors ~
For typedef actions, when a new type object of the typedef type is created, it should be clear which delete form should be used to delete the object.
Consider the following example:
Typedef std: string AddressLines [4]; // each person's address has four rows. Each row is a string.
// AddressLines is an array. If new is used as follows:
Std: string * pal = new AddressLines; // returns a string * the same as new string [4 ].
Then you must match the delete [] in the "array form":
Delete pal; // action not defined !!! Delete [] pal; // OK
To avoid such errors, we recommend that you do not perform typedef actions on arrays. Instead, you can use templates such as vector <string>.