Zen API
 All Classes Files Functions Variables Typedefs Macros Groups Pages
Reference Counting

All classes derived from kObject are reference counted. Reference counting can be used to share read-only or thread-safe object instances within different areas of a program.

Initially, the reference count of each object is set to one. The kObject_Share method can be used to increase the reference count, and the kObject_IsShared method can be used to determine if the reference count is currently greater than one. When an object is destroyed (or disposed), the reference count is decremented. The resources associated with an object are deallocated only when the reference count reaches zero.

kArray2 array = kNULL;
//construct a two-dimensional array (ref count: 1)
kCheck(kArray2_Construct(&array, kTypeOf(k64f), 100, 200, kNULL));
//increment the array's reference count (ref count: 2)
//the first time that the array is destroyed, its reference count will be decremented,
//but the array itself will not be deallocated (ref count: 1)
//the second time that the array is destroyed, its reference count will reach zero,
//and the array will be deallocated (ref count: 0)

A kObject reference count is a 32-bit integer (k32s) that is internally manipulated using operations from the kAtomic class (e.g. kAtomic_Increment32s). The use of atomic data operations enables reference counting methods to be used safely and efficiently across multiple threads.

See also
kObject_Share, kObject_IsShared, kObject_Destroy, kObject_Dispose