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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access