References in C++
What a C++ reference is, pass by reference vs pass by value, const references, and references vs pointers.
A reference is another name for an existing object: int &r = x; means using r is using x. Unlike a pointer, a reference must be bound when it's created, can't be null, and can't be re-pointed.
References shine as parameters:
void f(int &x)lets the function change the caller's variable.void f(const std::string &s)avoids copying a big object while promising not to change it. This is the everyday way to pass objects you only read.
Never return a reference to a local variable: the local is destroyed when the function returns.
Example
#include <iostream>
#include <string>
void shout(std::string &s) { s += "!"; }
std::size_t len(const std::string &s) { return s.size(); }
int main() {
std::string msg = "hello";
shout(msg);
std::cout << msg << " " << len(msg) << "\n";
return 0;
}
Output:
hello! 6
Watch it run: References are another name