Chapter 19: Smart Pointers

Memory management is central to systems programming. In C, pointers are pervasive—raw memory addresses managed manually with malloc() and free(). Rust takes a different approach by defaulting to stack allocation and using safe, borrow-checked references. Still, Rust provides specialized types called smart pointers for scenarios that require heap allocation, shared ownership, interior mutability, or other advanced ownership patterns.

This chapter introduces Rust’s smart pointers, compares them to pointers in C and C++ smart pointers, and explains how they integrate with Rust’s ownership and borrowing rules. We start with Box<T>, the simplest variant, then discuss Rc<T>, Arc<T>, and types that enable interior mutability. Along the way, we’ll clarify when and why you might need these tools, given that many Rust programs can be written using only stack-allocated data, references, and high-level abstractions like Vec<T> and String.