Smart Pointers
An ordinary reference &T only borrows someone else's value. A smart pointer is a struct that acts like a pointer but owns the data itself. Two traits make it "smart": Deref lets you dereference it with the * operator and pass it where a reference is expected, and Drop frees what it owns when the owner goes out of scope. By this definition String and Vec<T> are smart pointers too: they own a buffer on the heap and dereference to &str and &[T].
The standard library offers a smart pointer for each ownership rule that sometimes gets in the way. Box<T> puts a value on the heap and keeps a single owner for it — that is how recursive types and collections of trait objects are built. Rc<T> gives a value several owners and frees it when the reference count drops to zero. RefCell<T> moves the check of the borrowing rules from compile time to run time: you can change data through a shared reference, but breaking the rules becomes a panic. Weak<T> refers to a value without owning it and breaks the cycles that make Rc leak. Cow<'a, str> borrows a string until it needs to change it.
Each of these freedoms has its price: an allocation, a counter, a check at run time. Rc and RefCell work on one thread only, and their multithreaded twins Arc and Mutex are covered in the concurrency topic. This topic walks smart pointers layer by layer — from Box to Cow.
Topic map
- Box and the Heap —
Box::newputs a value on the heap, and an 8-byte pointer stays on the stack; a recursive type withoutBoxgives E0072;Vec<Box<dyn Trait>>holds values of different types; moving aBoxcopies only the pointer. - Deref and Drop —
*xfor your own type becomes*(x.deref()); deref coercion turns&Box<String>and&Rc<String>into the&stryou need;Dropfrees the resource,std::mem::dropdoes it earlier, and calling.drop()directly gives E0040. - Rc and Shared Ownership —
Rc::clonebumps a counter rather than copying the data;Rc::strong_count; through anRcyou can only read (E0596); anRccannot be sent to another thread (E0277),Arcexists for that. - RefCell and Interior Mutability — changing data through
&self;CellforCopyvalues;borrowandborrow_mutcheck the rules at run time and panic withRefCell already borrowed;try_borrow_mut; theRc<RefCell<T>>pairing. - Weak and Reference Cycles — a cycle of
Rcs never brings the count down to zero, and memory leaks;Rc::downgradegives aWeak,upgradereturns anOption<Rc<T>>; a tree where children belong to the parent and the link to the parent is weak. - Cow and Clone-on-Write —
Cow::BorrowedandCow::Owned; a function returns its input without an allocation when there is nothing to change;to_mutclones on the first write,into_ownedonly if the data is borrowed;Cow<'static, str>.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Declaring a recursive enum without indirection: enum List { Cons(i32, List), Nil } | error[E0072]: recursive type `List` has infinite size — you need a Box<List>, whose size is known |
Thinking Rc::clone copies the data | It only increments the reference count: both copies look at one value, and the data is freed when the count reaches zero |
Changing a value through an Rc: shared.push(4) for an Rc<Vec<i32>> | error[E0596]: cannot borrow data in an `Rc` as mutable — you need Rc<RefCell<T>> or Rc::make_mut |
Passing an Rc to thread::spawn | error[E0277]: `Rc<i32>` cannot be sent between threads safely — the counter of an Rc is not atomic; threads take Arc |
Holding the Ref from borrow() and calling borrow_mut() on the same RefCell | The code compiles but panics at run time with RefCell already borrowed |
Linking nodes with Rc in both directions | A cycle: the counts never drop to zero, Drop does not run, memory leaks — the back link is made Weak |
Building a huge array through Box::new([0u8; 16 * 1024 * 1024]) | In a debug build the array is first created on the stack, and the thread dies with has overflowed its stack; vec![0u8; n].into_boxed_slice() is safer |
Why it matters in interviews
Smart pointers are asked at the middle level as a check that the candidate understands ownership beyond its rules: why a recursive type needs Box, what exactly Rc::clone copies, why RefCell panics instead of refusing to compile. At senior level they add the memory layout, the price of the atomic counter in Arc and reference cycles in trees and graphs.
What interviewers usually check:
- What makes a pointer "smart" and why
StringandVecare smart pointers too. - When you cannot do without
Box<T>: recursive types, trait objects, large values. - What deref coercion is and how
&Box<String>turns into&str. - How
Box,RcandArcdiffer in ownership, threads and the behavior ofclone. - How interior mutability works:
CellversusRefCell, the check at run time, the panic andRc<RefCell<T>>. - How
Rcleaks through a cycle and howWeakbreaks it, for example in a tree with links to the parent.