On Fri, 2007-05-25 at 10:00 +1000, [EMAIL PROTECTED] wrote: > Thanks for explaining what a reference is, but it's wasted on me.
A reference is an alias for the location of the value it was initialised
with. "Alias"? An example:
int x = 4;
int &r = x;
r = 5;
anything you do to r actually happens to x,
anything you do to x looks as if it happened to r as well.
In the above example x is set to 5.
Not useful by itself, but hugely useful in function parameters
/**
* Read one line of text from stdin
*
* @returns
* true if successful, return false at EOF.
*
* @param result
* Puts the text of the line here.
*/
bool
read_one_line(string &result)
{
...
}
(Doxygen is your friend.) The absence of "const" indicates it is a
"return by reference" API, The converse
void
print_one_line(const string &text)
{
...
}
promises faithfully NOT to alter the value of the line of text being
printed.
How does it actually work? As Erik said, references are pointers in
disguise. In order for our x&r example, above, to work r is implemented
as an "always dereferenced" pointer. If you translated the C++ into C,
as the original AT&T cfront used to do, you get code like this:
int x = 4;
int *r = &x;
*r = 5;
This is because, if you want all things done to r to actually be done to
x, r has to know where x *is*, and that means a memory pointer.
The other useful thing about const references is that the compiler can
dereference the implicit pointer *once* when it is optimising, if that
helps. Therefore, write the code as naturally as possible, and let the
compiler optimise for you.
(The "volatile" sermon is for another day.)
Regards
Peter Miller <[EMAIL PROTECTED]>
/\/\* http://miller.emu.id.au/pmiller/
PGP public key ID: 1024D/D0EDB64D
fingerprint = AD0A C5DF C426 4F03 5D53 2BDB 18D8 A4E2 D0ED B64D
See http://www.keyserver.net or any PGP keyserver for public key.
"Rules of Optimization:
Rule 1: Don't do it.
Rule 2 (for experts only): Don't do it yet."
-- M.A. Jackson
signature.asc
Description: This is a digitally signed message part
_______________________________________________ coders mailing list [email protected] http://lists.slug.org.au/listinfo/coders
