Avoid returning pointers without allocation

When you return an internal pointer to an internal object, you reveal the object's existence. Consider what this revelation will cost you in the future. It doesn't matter whether the object is a direct member of the called object, or whether it is allocated and pointed to by the called object. If you return a pointer from a function and you're not allocating memory, and if the pointer points to an independent object that is already visible to the caller, there is no problem. (Although in any open network of data structures you must think carefully about memory management, concurrency, and so on--but that's another problem.)

If you simply return an internal pointer, you must consider that the caller can retain and use this pointer for an arbitrarily long time.

A better approach is to bound the use of the subobject by requiring callers to declare when they are done with it. For example, imagine member functions (like UseObject) that return a modifiable pointer to the subobject, and those that (like DoneWithObject)invalidate that pointer and give the container a chance to react to any changes. This approach is also good for const
pointers, as it gives you a chance to synthesize the subobject if you don't want it around all the time (you can delete the synthesized object at the DoneWithObject call). Of course, this only works for one client at a time.

Even better is to use the lifetime of a lightweight object to bound the access to the subobject, rather than explicit UseObject and DoneWithObject calls.

The best approach is not to return pointers to subobjects. Instead, use lightweight surrogate objects to set and get subobjects by value, and to obviate the need for pointers. This technique also works with concurrency. For more on this technique, see "Surrogate objects" on page 121.

[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker