Smart Pointers
Box, Rc, Arc, RefCell, Cell, Weak and Cow — heap allocation, shared ownership, interior mutability, reference cycles, and how Deref and Drop make smart pointers work.
A smart pointer is a struct that acts like a pointer (via the Deref trait) and owns extra capabilities: heap allocation, reference counting, runtime borrow checking. String and Vec<T> are smart pointers too. They extend ownership for cases single ownership can't express.
| Type | Ownership | Mutability | Thread-safe | Use for |
|---|---|---|---|---|
Box<T> | Single owner, heap | Through &mut | If T is | Recursive types, large values, trait objects |
Rc<T> | Shared (refcounted) | Immutable | No | Graphs, shared read-only data in one thread |
Arc<T> | Shared, atomic refcount | Immutable | Yes | Sharing data across threads |
RefCell<T> | Single owner | Interior (runtime-checked) | No | Mutating through a shared reference |
Cell<T> | Single owner | Interior (copy in/out) | No | Small Copy values (counters, flags) |
Mutex<T> / RwLock<T> | Single owner | Interior, locked | Yes | Shared mutable state across threads |
Weak<T> | Non-owning | — | With Arc | Breaking cycles, parent pointers, caches |
Cow<'a, T> | Borrowed or owned | Clone on write | — | Avoiding copies when mutation is rare |
Box: heap allocation
let b = Box::new(5); // the i32 lives on the heap; b (a pointer) on the stack
println!("{}", *b + 1); // deref like a reference
// Recursive types need indirection: otherwise the size would be infinite
enum List {
Cons(i32, Box<List>),
Nil,
}
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
// Trait objects
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];When the Box is dropped, its heap value is dropped too. No overhead beyond the allocation.
Rc: shared ownership (single thread)
When several parts of a program need to own the same data and you can't say which finishes last (a node referenced from several places, shared configuration), use reference counting:
use std::rc::Rc;
let shared = Rc::new(vec![1, 2, 3]);
let a = Rc::clone(&shared); // increments the count — cheap, no deep copy
let b = Rc::clone(&shared);
println!("{}", Rc::strong_count(&shared)); // 3
drop(a); // 2; the Vec is freed when the count reaches 0Rc<T> gives only shared (immutable) access. It's not Send: the non-atomic count would race across threads — the compiler won't let you try.
Arc: shared ownership across threads
Same as Rc but with atomic reference counting (slightly slower):
use std::sync::Arc;
use std::thread;
let config = Arc::new(load_config());
let handles: Vec<_> = (0..4).map(|i| {
let cfg = Arc::clone(&config);
thread::spawn(move || worker(i, &cfg))
}).collect();Interior mutability: RefCell and Cell
The borrow rules (one &mut or many &) are checked at compile time. Sometimes you know a mutation is safe but the compiler can't prove it — e.g. mutating a cache inside a method that takes &self. Interior mutability moves the check to runtime:
use std::cell::RefCell;
struct Memo {
cache: RefCell<std::collections::HashMap<u64, u64>>,
}
impl Memo {
fn fib(&self, n: u64) -> u64 { // &self, yet we mutate the cache
if n < 2 { return n; }
if let Some(&v) = self.cache.borrow().get(&n) { return v; }
let v = self.fib(n - 1) + self.fib(n - 2);
self.cache.borrow_mut().insert(n, v); // panics if already borrowed
v
}
}borrow() and borrow_mut() track borrows at runtime; violating the rules (a borrow_mut while a borrow is alive) panics instead of failing to compile. Cell<T> is a cheaper variant for Copy values: get() and set() with no borrowing at all.
Rc of RefCell: shared mutable data
The common single-threaded combination:
use std::{rc::Rc, cell::RefCell};
let account = Rc::new(RefCell::new(100));
let alice = Rc::clone(&account);
let bob = Rc::clone(&account);
*alice.borrow_mut() -= 30;
*bob.borrow_mut() += 10;
println!("{}", account.borrow()); // 80The thread-safe equivalent is Arc<Mutex<T>> (or Arc<RwLock<T>>) — see Fearless concurrency.
Reference cycles and Weak
Reference counting can't free cycles: if A holds an Rc to B and B holds an Rc to A, both counts stay ≥ 1 forever — a memory leak (safe, but a leak). Break cycles with Weak<T>, a non-owning reference that doesn't keep the value alive:
use std::rc::{Rc, Weak};
use std::cell::RefCell;
struct Node {
value: i32,
parent: RefCell<Weak<Node>>, // child → parent: weak
children: RefCell<Vec<Rc<Node>>>, // parent → children: strong
}
let leaf = Rc::new(Node { value: 3, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]) });
let branch = Rc::new(Node { value: 5, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![Rc::clone(&leaf)]) });
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);
if let Some(p) = leaf.parent.borrow().upgrade() { // Weak → Option<Rc>
println!("parent = {}", p.value);
}Trees with parent pointers, observer lists and caches are the classic uses. (Many Rust programmers avoid pointer-heavy graphs altogether and use arenas with indices — Vec<Node> plus usize IDs — which is simpler and faster.)
Deref and Drop
Dereflets*ptrand method calls go through to the inner value; deref coercion converts&Box<String>→&String→&strautomatically when calling functions.Dropruns cleanup when the pointer is dropped: decrementing a refcount, freeing memory, releasing a lock (MutexGuard).
Cow: clone on write
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_")) // allocate only when we must change it
} else {
Cow::Borrowed(input) // zero-copy in the common case
}
}- Box puts values on the heap: recursive types, big values, trait objects.
- Rc (single thread) and Arc (threads) give shared ownership via reference counting.
- RefCell and Cell provide interior mutability with runtime borrow checks; Rc of RefCell for shared mutable data in one thread, Arc of Mutex across threads.
- Rc cycles leak; break them with Weak (or use arenas with indices).
- Deref and Drop make smart pointers transparent and self-cleaning; Cow avoids needless copies.