Home | Overview | How Do I | Sample | Tutorial
This article explains how to delete all objects in a collection (without deleting the collection object itself).
To delete all the objects in a collection of CObjects (or of objects derived from CObject), you use one of the iteration techniques described in the article Collections: Accessing All Members of a Collection to delete each object in turn.
Caution Objects in collections can be shared. That is, the collection keeps a pointer to the object, but other parts of the program may also have pointers to the same object. You must be careful not to delete an object that is shared until all the parts have finished using the object.
This article shows you how to delete the objects in:
To delete all objects in a list of pointers to CObject
The following example shows how to delete all objects from a list of CPerson
objects. Each object in the list is a pointer to a CPerson
object that was originally allocated on the heap.
CTypedPtrList<CObList, CPerson*> myList;
POSITION pos = myList.GetHeadPosition();
while( pos != NULL )
{
delete myList.GetNext( pos );
}
myList.RemoveAll();
The last function call, RemoveAll, is a list member function that removes all elements from the list. The member function RemoveAt removes a single element.
Notice the difference between deleting an element’s object and removing the element itself. Removing an element from the list merely removes the list’s reference to the object. The object still exists in memory. When you delete an object, it ceases to exist and its memory is reclaimed. Thus, it is important to remove an element immediately after the element’s object has been deleted so that the list won’t try to access objects that no longer exist.
To delete all elements in an array
The code for deleting all elements of an array is as follows:
CArray<CPerson*, CPerson*> myArray;
int i = 0;
while (i < myArray.GetSize() )
{
delete myArray.GetAt( i++ );
}
myArray.RemoveAll();
As with the list example above, you can call RemoveAll to remove all elements in an array or RemoveAt to remove an individual element.
To delete all elements in a map
The code for deleting all elements of a CMap collection is as follows. Each element in the map has a string as the key and a CPerson
object (derived from CObject) as the value.
CMap<CString, LPCSTR, CPerson*, CPerson*> myMap;
// ... Add some key-value elements ...
// Now delete the elements
POSITION pos = myMap.GetStartPosition();
while( pos != NULL )
{
CPerson* pPerson;
CString string;
// Gets key (string) and value (pPerson)
myMap.GetNextAssoc( pos, string, pPerson );
delete pPerson;
}
// RemoveAll deletes the keys
myMap.RemoveAll();
You can call RemoveAll to remove all elements in a map or RemoveKey to remove an individual element with the specified key.