Tools.h++ Manual
12-2 104011 Tandem Computers Incorporated
12
Storage methods
There are two different ways to store an object in a collection: either store the
object itself (value-based collections) or store a pointer or reference to the object
(reference-based collections). The difference can have important consequences.
Value-based collections are simpler to understand and manipulate. You create,
say, a linked list of integers or doubles. Or a hash table of shorts. The stored
type can be more complicated: for example,
RWCStrings
. The important point
is that, even though the stored type may contain pointers to other objects (as
does
RWCString
), they act as if they are values. When an object is inserted
into a value-based collection, a copy is made. An analogy is C's pass-by-value
semantics in function calls.
In a reference-based collection, you store and retrieve pointers to other objects.
For example, you could create a linked list of pointers to ints or doubles. Or a
hash table of pointers to
RWCStrings
. This type of collection can be very
efficient because pointers are small and inexpensive to manipulate, but you
must be aware of the lifetime of the pointed-to objects, lest you create two
pointers to the same object and then prematurely delete the object, leaving the
second pointer pointing into nonsense.
In general, with a reference-based collection you are responsible for the
creation, maintenance and destruction of the actual objects themselves,
although the Tools.h++ classes have a few member function to help you do
this.
Having said this, reference-based collections shouldn't scare you. In the vast
majority of the cases, the "ownership" of the contained objects is perfectly
obvious. Furthermore, reference-based collections enjoy certain performance
and size advantages because the size of all pointers is the same, allowing a
large degree of code reuse. You may also want to simply point to an object
rather than contain it (a set of selected objects in a dialog list is an example that
comes to mind). Finally, for some kinds of heterogeneous collections, they may
be the only viable approach.
It is important to note that there is a transition between the two types: one
person's value is another person's pointer! You can always use a value-based
collection class to create a reference-based collection by using addresses (i.e.,
pointers) as the inserted type. But, the resulting programming interface may
well be unpleasant and clumsy.