Zen API

- Home
- Topics
- Types
- Files

All Classes Files Functions Variables Typedefs Friends Macros Modules Pages
Object Destruction

There are two ways to destroy an object derived from the kObject class: kObject_Destroy and kObject_Dispose. Both of these methods will destroy the object itself, but kObject_Dispose will also destroy any aggregated child objects.

The purpose of kObject_Dispose is to allow arbitrary hierarchies of connected objects to be deallocated in a single call, rather than having to traverse the hierarchy, destroying each object in turn. For example, consider a list object that contains images (kArrayList<kImage>). The list class represents a data collection; it contains references to images that have been added to the collection, but it does not own the image objects. kObject_Destroy will destroy the list but will not automatically destroy the list elements (in this case, images). kObject_Dispose will destroy both the list object and the images contained in the list:

kArrayList list = kNULL;
kImage image = kNULL;
kBool useDispose = kTRUE;
kSize i;
//construct a list that will hold objects
kCheck(kArrayList_Construct(&list, kTypeOf(kObject), 0, kNULL));
//add a few images to the list
for (i = 0; i < 10; ++i)
{
kCheck(kImage_Construct(&image, kTypeOf(kRgb), 1024, 768, kNULL));
kCheck(kArrayList_Add(list, &image));
}
//there are two ways to destroy the list and its elements
if (useDispose)
{
//the dispose method destroys both the list and its elements in a single call
kCheck(kObject_Dispose(list));
}
else
{
//alternatively, the destroy method can be used to destroy each object in turn
for (i = 0; i < kArrayList_Count(list); ++i)
{
kObject item = kArrayList_As_(list, i, kObject);
kCheck(kObject_Destroy(item));
}
kCheck(kObject_Destroy(list));
}

The difference between kObject_Dispose and kObject_Destroy is best understood in terms of the relationship between the parent object and its children. If the parent object strictly owns its children (composition), then the children will always be destroyed when the parent is destroyed. But if the parent merely contains its children (aggregation), then the children will only be destroyed by using kObject_Dispose.

Most classes, aside from those designed to serve as data collections (e.g. kArrayList, kQueue), respond identically to kObject_Destroy or kObject_Dispose, because child objects are typically owned by the parent object. Refer to the documentation for each class to determine if it has aggregated child elements that can be destroyed using kObject_Dispose.

Note to implementers: If you are implementing a data collection that will support kObject_Dispose, remember to override the kObject_VDisposeItems method. The DisposeItems method is called by kObject_Dispose to handle child elements.

See also
  kObject_Destroy, kObject_Dispose, Reference Counting