|
|
|
|
|
|
|
Cat #499: 997
Cat #500: 999 |
|
|
|
|
|
|
|
|
Analysis: Line 26 declares the array Family, which holds 500 CAT objects. The entire array is created on the free store with the call to new CAT[500]. |
|
|
|
|
|
|
|
|
Each CAT object added to the array also is created on the free store (line 31). Note, however, that the pointer isn't added to the array this time; the object itself is. This array isn't an array of pointers to CATsit is an array of CATs. |
|
|
|
|
|
|
|
|
Deleting Arrays on the Free Store |
|
|
|
|
|
|
|
|
Family is a pointera pointer to the array on the free store. When, on line 33, the pointer pCat is dereferenced, the CAT object itself is stored in the array. (Why not? The array is on the free store.) But pCat is used again in the next iteration of the loop. Isn't there a danger that there is now no pointer to that CAT object, and a memory leak is created? |
|
|
|
|
|
|
|
|
This would be a big problem, except that deleting Family returns all the memory set aside for the array. The compiler is smart enough to destroy each object in the array and to return its memory to the free store. |
|
|
|
|
|
|
|
|
To see this, change the size of the array from 500 to 10 in lines 26, 29, and 37. Then uncomment the cout statement in line 21. When line 40 is reached and the array is destroyed, each CAT object destructor is called. |
|
|
|
|
|
|
|
|
When you create an item on the heap by using new, you always delete that item and free its memory with delete. Similarly, when you create an array by using new<class>[size], you delete that array and free all its memory with delete[]. The brackets signal to the compiler that this array is being deleted. |
|
|
|
|
|
|
|
|
If you leave the brackets off, only the first object in the array will be deleted. You can prove this to yourself by removing the brackets on line 39. If you edited line 21 so that the destructor prints, you should then see only one CAT object destroyed. Congratulations! You just created a memory leak. |
|
|
|
|
| DO | DON'T | | DO remember that an array of n items is numbered from 0 through n-1. | DON'T write or read past the end of an array. | | DO use array indexing with pointers that point to arrays. | DON'T confuse an array of pointers with a pointer to an array. |
|
|
|