Objects On The Stack

Use the stack to ensure efficiency and reduce complexity.

C++ programs that make good use of exceptions move as much data from the heap to the stack as possible. This ensures that destructors run and memory is released when an exception occurs. It also reduces the complexity of the program by eliminating many pointers, reducing the chances of memory leaks, and letting the compiler ensure that objects are valid (as opposed to pointers that could be NULL or bad).

To ensure objects are used on the stack efficiently, most CD objects store their data externally. The following example is of an iterator object that holds 500 statistics records:

When the iterator is created, an iterator data object is also created to hold the records. The data object also has a reference count that indicates how many objects are using the data. When an object is copied, the new object (the copy) is linked to the data and the reference count of the data object is incremented. There are still only 500 records (not 1000), and the reference count is now 2.

When connected objects are destroyed, they decrement the reference count in the data object. When the reference count reaches 0, the data object is also destroyed. The following figure provides an example of the efficiency possible when shared data is copied:
 1. void Func() 
 2. ( 
 3. Iterator itFinal = CreateIterator(); 
 4. } 
 5. 
 6. Iterator CreateIterator() 
 7. { 
 8. CSomeCmd cmd(...); 
 9. Iterator itLocal = node.Execute(cmd); 
 10. return itLocal; 
 11. }

On line 3 the sample code calls the CreateIterator() function. The CreateIterator() function returns an iterator, called itLocal. This iterator is created on line 9 and returned on line 10.

At line 11 the C++ compiler creates a temporary copy of itLocal before destroying it. As part of the copy, the iterator data reference count is incremented to 2. When itLocal is destroyed, the reference count drops to 1 so that the records are not deleted.

Next, the C++ compiler constructs itLocal on line 3 by passing the temporary to its copy constructor. The reference count is again incremented to 2 because both iterators are pointing to it. The temporary is then destroyed, reducing the reference count to 1.

The result is that an unlimited number of records are passed to the stack with little more than the copying of two pointers and some reference counting.