References and pointers
A copy is a new object, a reference is a new name, and a pointer is a new object that holds an address.
- Predict which of copy, reference and pointer changes the original
- Pass large objects to functions by reference instead of by value
- Know when to prefer a reference and when a pointer is needed
Three lines that look alike do three very different things:
int b = a; // copy: a new int with the same value
int &d = c; // reference: another name for c, no new int
int *p = &a; // pointer: a new variable that stores a's address
Copies
12references.cpp starts with int b = a; b += 1; and prints a = 5, b = 6: changing the copy leaves the original alone, and &a and &b are different addresses.
References
int c = 5;
int &d = c;
d += 1;
// c = 6, d = 6, and &c == &d
A reference must be bound when it is declared and can never be re-bound or be null. It is not a new object at all — just another name for c.
Pointers
13pointers.cpp stores an address:
int a = 5;
int *b = &a; // & takes the address
*b += 1; // * follows it: a is now 6
std::cout << b; // prints the address, e.g. 0x7ffd...
A pointer is a real 8-byte variable (on x86-64). It can be re-pointed, and it can be nullptr — which is both its power and its danger. revision/01_pointer_vs_reference.cpp makes the trade-off explicit: increment(int *number) must trust that the caller did not pass a null or dangling pointer, while increment_ref(int &number) always refers to a real object.
Passing to functions
12passby_reference.cpp shows why this matters for performance and correctness:
void add_elements_passby_value(std::vector<int> vector, int N); // works on a copy
void add_elements_using_reference(std::vector<int> &vector, int N);
After calling the by-value version, my_vector is still empty — the ten push_backs went into a copy that was destroyed at the end of the function. The by-reference version fills the caller’s vector with 0 1 2 … 9.
The rule of thumb that falls out:
| You want to… | Parameter |
|---|---|
| read a small value (int, double) | int x |
| read a large object | const std::vector<int> &v |
| modify the caller’s object | std::vector<int> &v |
| express “maybe no object” | T *p (check for nullptr) |
Try it yourself. Write int &bad() { int x = 42; return x; }, call it and print the result. Compile with -Wall and read the warning, then run it. The local x dies when the function returns, so the reference dangles — exactly the mistake revision/03_memory_management.txt warns about. (g++ 13 knows this too: it compiles the return as a null address, so the program crashes with a segmentation fault instead of printing 42 by luck.)