Deleting Arrays on the Heap

Family is a pointer—a pointer to the new CAT array on the heap. 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 heap.) 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 heap.

To see this, change the size of the array from 500 to 10 in lines 24, 27, and 35. Then uncomment the cout statement in line 19. When line 39 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[] followed by the name of the array. Similarly, when you create an array by using new <class>[size], you delete that array and free all its memory with delete[] <class>. The empty brackets signal to the compiler that this entire 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.
DO use array indexing with pointers that point to arrays.
DON'T write or read past the end of an array.
DON'T confuse an array of pointers with a pointer to an array.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.136.226