Tuesday, January 08, 2008

Reference

All are from C++ faqs
In the following example, the first two change i

void f(int& x, int* y, int z) throw()
{
x = 5; //main()'s i changed to 5
*y = 6; //main()'s i changed to 6
z = 7; //no change to main()'s i
}

int main()
{
int i = 4;
f(i, &i, i);
}

Another example:

int i = 5;
int j = 6;
int& k = i;
k = j; // k = 6 but k doesn't bind to j

A pointer should be thought of as a separate object with its own distinct set of operations (*p, p->blah, and so on). So creating a pointer creates a new object. In contrast, creating a reference does not create a new object; it merely creates an alternative name for an existing object.

Pointers are required when it might be necessary to change the binding to a different referent or to refer to a nonobject (a NULL pointer). The only time a parameter or return value should be a pointer is when the function needs to accept or return a sentinel value. In this case the function can accept or return a pointer and use the NULL pointer as the sentinel value.

No comments:

Post a Comment