|
storage.
References in functions
The most common place you’ll see
references is as function arguments and return values. When a reference is used
as a function argument, any modification to the
reference inside the function will cause changes to the argument
outside the function. Of course, you could do the same thing by passing a
pointer, but a reference has much cleaner syntax. (You can think of a reference
as nothing more than a syntax convenience, if you want.)
If you return a
reference from a function, you must take the same care as if you return a
pointer from a function. Whatever the reference is connected to shouldn’t
go away when the function returns, otherwise you’ll be referring to
unknown memory.
//: C11:Reference.cpp
// Simple C++ references
int* f(int* x) {
(*x)++;
return x; // Safe, x is outside this scope
}
int& g(int& x) {
x++; // Same effect as in f()
return x; // Safe, outside this scope
}
int& h() {
int q;
//! return q; // Error
static int x;
return x; // Safe, x lives outside this scope
}
int main() {
int a = 0;
f(&a); // Ugly (but explicit)
g(a); // Clean (but hidden)
} ///:~
The call to f( )
doesn’t have the convenience and cleanliness of using references, but
it’s clear that an address is being passed. In the call to
g( ), an address is being passed (via a reference), but you
don’t see it.
|
|