|
|
|
|
References in C++
A reference
(&) is like a constant pointer that is
automatically dereferenced. It is usually used for function argument lists
and function return
values. But you can also make a
free-standing reference. For
example,
//: C11:FreeStandingReferences.cpp
#include <iostream>
using namespace std;
// Ordinary free-standing reference:
int y;
int& r = y;
// When a reference is created, it must
// be initialized to a live object.
// However, you can also say:
const int& q = 12; // (1)
// References are tied to someone else's storage:
int x = 0; // (2)
int& a = x; // (3)
int main() {
cout << "x = " << x << ", a = " << a << endl;
a++;
cout << "x = " << x << ", a = " << a << endl;
} ///:~
In line (1), the compiler allocates a
piece of storage, initializes it with the value 12, and ties the reference to
that piece of storage. The point is that any reference must be tied to someone
else’s piece of storage. When you access a reference, you’re
accessing that storage. Thus, if you write lines like (2) and (3), then
incrementing a is actually incrementing x, as is shown in
main( ). Again, the easiest way to think about a reference is as a
fancy pointer. One advantage of this “pointer” is that you never
have to wonder whether it’s been initialized (the compiler enforces it)
and how to dereference it (the compiler does it).
There are certain rules when using
references:
- A reference must be
initialized when it is created. (Pointers can be initialized at any
time.)
- Once a
reference is initialized to an object, it cannot be changed to refer to another
object. (Pointers can be pointed to another object at any
time.)
- You cannot
have NULL references. You must always be able to assume that a reference is
connected to a legitimate piece of
|
|
|