Tools.h++ Manual
104011 Tandem Computers Incorporated 13-5
13
Pointer-based collections
The final type of collection, pointer-based, is similar to the Smalltalk-like
collection classes. The data that gets inserted into the collection is not the
object itself, but rather its address. That is, a pointer to the data is inserted.
Now the collection class refers to the original object:
/* A 100 element array of pointers to RWCStrings: */
RWTPtrVector<RWCString> v(100);
RWCString s("A string");
v[2] = &s;
Both the object
s
and the array element
v[2
] refer to the same object.
Naturally, this approach requires some care: should the string be deleted the
array element will be left pointing into nonsense. You must take care that you
are aware of who is responsible for the allocation and deallocation of objects
collected this way.
Neverthless, this type of collection can be appropriate for many situations.
You may need to have the same group of objects referred to in many ways,
requiring that each collection point to the target objects, rather than wholy
contain them. For example, a collection may refer to a set of "picked" objects
that your graphical program has obtained from a user. You need to know
which ones must be highlighted.
13.4 An example
It's time to look at an example. Let's start with a simple one: a vector of
doubles.
Code Example 13-1
#include <rw/tvvector.h> // 1
main() {
RWTValVector<double> vec(20, 0.0); // 2
int i;
for (i=0; i<10; i++) vec[i] = 1.0; // 3
for (i=11; i<20; i++) vec(i) = 2.0; // 4