19.2 Smart Pointers vs. References
References (&T
and &mut T
):
- Provide non-owning, borrowed access to data.
- Never allocate or free memory themselves.
- Are enforced at compile time, ensuring a reference never outlives the data it refers to.
Smart Pointers:
- Own the data they point to and free it automatically when no longer needed.
- Enable patterns not possible with references alone, such as heap allocation, shared ownership, or interior mutability.
- Integrate deeply with Rust’s ownership and borrowing system, often catching errors at compile time, and in the case of interior mutability, at runtime.
- Are often unnecessary for simple tasks since Rust encourages stack allocation and provides built-in collections.
- Are used primarily when explicit heap allocation, shared ownership, or interior mutability are needed beyond what simple references or built-in collections provide.
- Strongly reduce memory-related errors compared to manual memory management approaches.