19.2 Smart Pointers vs. References

Distinguishing between references and smart pointers is fundamental:

References (&T and &mut T):

  • Borrow: Provide temporary, non-owning access to data owned by someone else.
  • No Memory Management: Do not allocate or deallocate memory.
  • Compile-Time Checked: Validity (lifetime) is checked entirely at compile time.
  • Zero-Cost (Typically): Usually have no runtime overhead compared to using the data directly.

Smart Pointers (e.g., Box<T>, Rc<T>, Arc<T>):

  • Own: Own the data they point to (often on the heap).
  • Manage Lifecycle: Responsible for resource cleanup (e.g., deallocation) via the Drop trait when they go out of scope.
  • May Allocate: Often, but not always, involve heap allocation (Box::new, Rc::new).
  • Add Behavior: Can incorporate features like reference counting, interior mutability checks, etc.
  • Safety Guaranteed: Integrate with Rust’s ownership system, ensuring safety through compile-time or runtime checks.
  • Indirection: Always involve a level of pointer indirection to access the underlying data.
  • Location: The smart pointer struct itself typically resides on the stack or within another data structure, while the data it points to is often on the heap.

In essence, references are like temporary lenses for viewing data, while smart pointers are wrappers that own and manage data, often living on the heap. Both are crucial tools in Rust for writing safe and efficient code.