Core Module
12 min forge
C++ Memory References
Understanding aliases and safer memory access without pointers.
C++ Memory References
π What is it
A reference is an alias, that is, another name for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable.
β‘ When to use
Recommended over pointers for function parameters and return values when the object is known to exist. It provides a cleaner syntax and is safer as it cannot be nullptr.
π§ Time complexity
- Access: $O(1)$
π» Code example
cpp Standardint x = 10; int &ref = x; // ref is an alias for x ref = 20; // x is now 20
β Common mistakes
- Trying to declare a reference without initializing it.
- Returning a reference to a local variable (Dangling reference).
- Thinking you can "re-seat" a reference to point to another variable after initialization.