Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Reference (C++)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Uses of references == The most convenient use of references is for function parameters. References allow you to read and change the values of function arguments (actual parameters) without having to use the dereference operator <code>*</code> every time the parameter is used. For example: <syntaxhighlight lang="cpp"> void Square(int x, int& out_result) { out_result = x * x; } </syntaxhighlight> Then, the following call would place 9 in ''y'': <syntaxhighlight lang="cpp"> int y; Square(3, y); </syntaxhighlight> However, the following call would give a compiler error, since lvalue reference parameters not qualified with <code>const</code> can only be bound to addressable values: <syntaxhighlight lang="cpp">Square(3, 6);</syntaxhighlight> * Returning an lvalue reference allows function calls to be assigned to:<syntaxhighlight lang="cpp"> int& Preinc(int& x) { return ++x; // "return x++;" would have been wrong } Preinc(y) = 5; // same as ++y, y = 5</syntaxhighlight> * In many implementations, normal parameter-passing mechanisms often imply an expensive copy operation for large parameters. References qualified with <code>const</code> are a useful way of passing large objects between functions that avoids this overhead:<syntaxhighlight lang="cpp"> void FSlow(BigObject x) { /* ... */ } void FFast(const BigObject& x) { /* ... */ } BigObject y; FSlow(y); // Slow, copies y to parameter x. FFast(y); // Fast, gives direct read-only access to y. </syntaxhighlight> If <code>FFast</code> actually requires its own copy of ''x'' that it can modify, it must create a copy explicitly. While the same technique could be applied using pointers, this would involve modifying every call site of the function to add cumbersome address-of (<code>&</code>) operators to the argument, and would be equally difficult to undo, if the object became smaller later on.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)