Use references for a one-time reference

C++ provides two mechanisms for accessing objects indirectly: pointers and references. By using pointers and references appropriately, you can increase the readability of your code by giving the reader hints as to what is going on. These mechanisms have a lot in common (indeed, they are implemented the same way), so it is important to know which one to use and when.

Use references when a parameter is to be passed by reference; the called function forgets about the argument as soon as it returns. Use a regular reference if you are going to modify the argument (TFoo&), and a const reference if you aren't going to modify it but don't want the overhead of call by value (const TFoo&).

Use pointers when the function you call retains a reference (an alias) to the object you are passing in, such as when you construct a dynamic data structure. For example, when you put an object into one of the Taligent Collection classes, the collection retains a pointer to your object. Explicitly using pointers lets the reader know that aliasing is occurring.

Developers sometimes pass in a nil pointer to indicate a default value. The correct way to achieve the same effect is to provide a reference with a static default argument, or to overload the function:

      class TFoo {
          static const TBar kDefault;
          Technique1(const TBar &arg = kDefault);
          Technique2(const TBar &arg);

[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