beautypg.com

A note on memory management – HP Integrity NonStop J-Series User Manual

Page 102

background image

A Note on Memory Management

A reference-based collection can be very efficient because pointers are small and inexpensive to
manipulate. However, with a reference-based collection, you must always remember that you
are responsible for memory management: the creation, maintenance, and destruction of the
actual objects themselves. If you create two pointers to the same object and prematurely delete
the object, you'll leave the second pointer pointing into nonsense. By the same token, you must
never insert a nil pointer into a reference-based collection, since the collection has methods
which must dereference its contained values.

Despite the added responsibility, don't avoid reference-based collections when you need them.
Tools.h++ classes have member functions to help you, and in most cases, the ownership of the
contained objects is obvious anyway. You should choose a reference-based collection if you
need performance and size advantages: here the size of all pointers is the same, allowing a large
degree of code reuse. Also choose the reference-based collection if you just want to point to an
object rather than contain it (a set of selected objects in a dialog list, for example). Finally, for
certain heterogeneous collections, the reference-based approach may be the only one viable.

This manual is related to the following products: