References
A reference is another name for an existing object, bound once when it is declared, and is the usual way to let a function change or cheaply read its caller's data.
Compare aliasing through a reference with copying a value or reseating a pointer.
A Rocket Run function should heal the player by 20 points. You write it, call it, and the player's health does not budge. The function worked on a copy. References are C++'s clean way of saying "not a copy, the real thing".
The rule
A reference is another name for an existing object, bound once, forever.
int health = 50;
int& hp = health; // hp is another name for health
hp += 20; // health is now 70Rules that make references simpler than pointers:
- A reference must be bound when it is declared.
int& hp;on its own is an error. - It can never be re-bound to a different object. Assigning to it assigns to the object it names.
- There is no null reference to check for, and no
*or->to write.
Their main job is function parameters:
void healCopy(int hp) { hp += 20; } // copy: caller unchanged
void heal(int& hp) { hp += 20; } // reference: caller changed
void showName(const std::string& name) { // read-only, no copy
std::cout << name << '\n';
}const T& is the everyday choice for passing large objects you only read: no copy is made, and const promises you will not change the caller's data.