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 Standard
int 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.