References & const
C++ adds references, aliases for existing variables that are harder to misuse than raw pointers, and treats const as a first-class design tool.
References
A reference is another name for an existing variable:
int x = 42;int &ref = x; // ref is a reference to xref = 100;std::cout << x << std::endl; // 100 - x changed through refUnlike pointers:
- References cannot be null (though one can still dangle: a reference to a local that has gone out of scope is as broken as a dangling pointer)
- References cannot be reassigned to point elsewhere
- References do not need dereferencing (no
*needed)
Predict: after these four lines, what are a, b and r?
int a = 1;int &r = a;int b = 2;r = b;b = 3;a is 2, b is 3 and r is 2. The line r = b doesn't make r refer to b. A reference is bound once, when it's created, and every later use of it means the original object, so r = b is exactly a = b: it copies the value 2 into a. Changing b afterwards has no effect on either of the others.
Pass by Reference
References shine in function parameters:
void swap(int &a, int &b) { int temp = a; a = b; b = temp;}
int x = 1, y = 2;swap(x, y); // x is now 2, y is now 1In C you'd reach for pointers (int *a, int *b) and dereference them by hand. References give you the same behaviour without the asterisks cluttering up the call site.
Worked Example: What a Reference Really Is
Trace swap(x, y) with real values. The addresses here are illustrative; yours will differ from run to run.
| Step | What happens | x at 0x7ffd1000 | y at 0x7ffd1004 |
|---|---|---|---|
| Call | a is bound to x, b to y. &a gives 0x7ffd1000, the same as &x | 1 | 2 |
int temp = a; | reads through a, so temp is 1 | 1 | 2 |
a = b; | writes 2 to the int at 0x7ffd1000 | 2 | 2 |
b = temp; | writes 1 to the int at 0x7ffd1004 | 2 | 1 |
No copies of x or y were made, and swap never saw their names. It only ever had their addresses. That's the honest description of a reference parameter. The standard doesn't say how references are stored, but in practice GCC and Clang pass an address, much as the C version would, and insert every * for you. Print &a inside swap and &x in the caller and you'll get the same number. The rules on top (bound once, never reseated, no null) are what the language adds.
That same machinery explains the dangling case. Return int & to a local variable and the caller gets the address of a stack slot that's already been handed back. The compiler will usually warn, but the code still builds.
const References
A const reference allows read-only access:
void print_name(const std::string &name) { std::cout << name << std::endl; // name = "other"; // ERROR: cannot modify const reference}const & is the default way to pass large objects in C++. No copy on the way in, no accidental mutation once it's there. Use it for any parameter you only need to read.
Two of these functions have a parameter bug. Predict what the first line prints before you run it, then fix both signatures.
const Correctness
In C++, const is used pervasively:
const int MAX_SIZE = 100; // compile-time constantconst std::string &ref = getName(); // const referencevoid display() const; // method that doesn't modify the objectThat middle line deserves a second look. If getName() returns a std::string by value, the result is a temporary that would normally die at the end of the statement. Binding it to a const reference extends the temporary's lifetime to match the reference, so ref stays valid for the rest of the scope. A non-const std::string & can't bind to the temporary at all, which is the compile error you hit with shout("hello") above.
When pointers get involved, read the declaration right to left. const int *p is a pointer to a const int: you can move p, but not change the value through it. int *const p is a const pointer to an int: the value can change, p can't be pointed elsewhere. A reference behaves like the second kind, with the const built in.
Marking things const when you can:
- Documents intent at the call site
- Turns whole categories of bugs into compile errors
- Hands the optimiser more to work with
constexpr
For values known at compile time, use constexpr:
constexpr int square(int x) { return x * x; }constexpr int result = square(5); // computed at compile timeconstexpr is the stronger guarantee, with a catch. When the result initialises a constexpr variable, as result does, the compiler has to work it out during compilation. Call the same square with a value only known at runtime and it simply runs at runtime, like any other function. If you need a guarantee that a function only ever runs at compile time, C++20's consteval gives you one.