References (C++)

Eksempel:

A reference is an alternative name for an object. The main use of references is for specifying arguments and return values for functions in general and for overloaded operators in particular. The notation X& means "reference to X". For example:

To ensure that a reference is a name for something, we must initialize the reference. For example:

Initialization of a reference is somehting quite different from assignment to it. Desipte appearances, no operator operates on a reference. For example:

The obvious implementation of a reference is as a (constant) pointer that is dereferenced each time it is used. It doesn't do much harm thinking about references that way, as long as one remembers that a reference isn't an object that can be manipulated the way a pointer is.

Initialization of a reference is trivial when the initializer is an lvalue (an object whose address you can take). The initializer for a T& must be an lvalue of type T.

The initializer for a const T& need not be an lvalue or even of type T. In such cases,
 * 1) first, implicit type conversion to T is applied if necessary;
 * 2) then, the resulting value is placed in a temporary variable of type T; and
 * 3) finally, this temporary variable is used as the value of the initializer.

Consider:

A reference can be used to specify a function argument so that the function can change the value of an object passed to it. For example:

To keep a program readable, it is often best to avoid functions that modify their arguments. Instead, you can return a value from the function explicitly or require a pointer argument:

The increment(x) notation doesn't give a clue to the reader that x's value is being modified, the way x = next(x) and incr(&x) does. Concequently "plain" reference arguments should be used only where the name of the funciton gives a strong hint that the reference argument is modified.