Sub topic 2
What makes a pointer smart
This chapter defines a smart pointer and shows what separates one from a plain reference. It assumes you know Rust's ownership, moves, and borrowing rules, can read basic traits and generics, and know the difference between the stack and the heap. Later chapters cover Box, Rc, and RefCell one at a time. Here you build the model they share.
A pointer is an address
A pointer is a value that holds a memory address. The data lives somewhere else, and you reach it by following the address. Rust has several kinds of pointer, and the most common is the reference, written &T or &mut T.
A reference does one job. It borrows a value that something else owns. It has no say over when that value is created or destroyed, and the borrow checker verifies that the reference never outlives its target. This makes references cheap and predictable. It also limits them. A reference cannot keep data alive, cannot decide where data is stored, and cannot share ownership.
What "smart" adds
A smart pointer is a data structure that acts like a pointer and also carries extra metadata or behavior. In Rust, the usual mark of a smart pointer is that it owns the data it points to. A reference only borrows.
The following types are all smart pointers:
Box<T>owns a value on the heap.Rc<T>owns a value together with otherRchandles and keeps a reference count.StringandVec<T>own a heap buffer and track its length and capacity.RefCell<T>is not a pointer in the strict sense, but it wraps a value and adds runtime borrow tracking. It is usually grouped with the smart pointers.
You have used smart pointers since your first Rust program. String and Vec<T> are smart pointers, even though nobody calls them that day to day.
The two traits behind the behavior
Two standard library traits give a type pointer-like behavior and automatic cleanup. Smart pointers are normally structs that implement both.
| Trait | What it provides | When it runs |
|---|---|---|
| `Deref` | Lets `*value` and method calls reach the inner data | When you use `*`, or when the compiler auto-dereferences |
| `Drop` | Runs cleanup code, such as freeing memory | When the owner goes out of scope |
Deref makes the type feel like a reference, so you can write code against the inner type without unwrapping anything by hand. Drop ties the lifetime of the resource to the lifetime of the owner. Together they mean you rarely free memory by hand, and you cannot forget to.
Neither trait is magic. They are ordinary traits, and you can implement them for your own types. The next example does that.
A first custom smart pointer
This type owns a value, forwards to it through Deref, and announces when it is released. A later chapter covers Deref and Drop in detail, so read this as a preview.
use std::ops::Deref;
struct Tracked<T> {
value: T,
label: &'static str,
}
impl<T> Deref for Tracked<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<T> Drop for Tracked<T> {
fn drop(&mut self) {
println!("releasing {}", self.label);
}
}
fn main() {
let name = Tracked {
value: String::from("Ferris"),
label: "name",
};
println!("{} has {} bytes", *name, name.len());
{
let inner = Tracked {
value: 7,
label: "inner",
};
println!("inner + 1 = {}", *inner + 1);
}
println!("end of main");
}The program prints:
Ferris has 6 bytes
inner + 1 = 8
releasing inner
end of main
releasing nameThree things are worth noticing.
*nameyields theStringinside, andname.len()works even thoughTrackedhas nolenmethod. The compiler followsDerefto find it.inneris released at the closing brace of its block, beforeend of mainprints.nameis released last, whenmainreturns. You never calleddropyourself.
How a smart pointer is laid out
A plain reference is one machine word, the address. A smart pointer is usually a struct whose fields include that address and possibly more.
use std::mem::size_of;
use std::rc::Rc;
fn main() {
println!("&i32 = {} bytes", size_of::<&i32>());
println!("Box<i32> = {} bytes", size_of::<Box<i32>>());
println!("Rc<i32> = {} bytes", size_of::<Rc<i32>>());
println!("&str = {} bytes", size_of::<&str>());
println!("String = {} bytes", size_of::<String>());
println!("Vec<i32> = {} bytes", size_of::<Vec<i32>>());
}On a typical 64-bit target this prints 8, 8, 8, 16, 24, and 24 bytes. The sizes show where the extra information lives:
Box<i32>andRc<i32>are one address. ABoxstores nothing else. AnRckeeps its counts next to the data on the heap, not in the handle.&stris 16 bytes because it is a "fat" pointer: an address plus a length.StringandVec<i32>are 24 bytes: an address, a length, and a capacity. The capacity is metadata that a plain reference has no room for.
References versus smart pointers
| Question | Reference `&T` | Smart pointer |
|---|---|---|
| Who owns the data? | Someone else | The pointer itself |
| Who frees the data? | Not the reference | The pointer, through `Drop` |
| Extra data stored? | None, except a length for slices | Yes, for example counts or capacity |
| Can it outlive its creator's scope? | No, the borrow checker forbids it | Yes, if it is moved |
| Rules enforced | Compile time | Depends on the type |
The last row matters most for this tutorial. Box<T> keeps the ordinary ownership rules and checks them at compile time. Rc<T> allows several owners. RefCell<T> moves the borrowing check to runtime. Each type bends one rule in a controlled way, and the rest of the tutorial examines each in turn.
Common mistakes
- Treating
&Tas if it owned data. A function that returns a reference to a local variable fails to compile, because the owner is dropped when the function ends. Return the owned value, or a smart pointer, instead. - Reaching for a smart pointer too early. A plain reference or an owned value is the right default. Use a smart pointer only when you need what it adds, such as heap storage, shared ownership, or runtime borrow checking.
- Assuming
Dropis a destructor you call. You cannot callvalue.drop()directly, because the compiler rejects it to prevent a double free. Usestd::mem::drop(value)to release a value early. The chapter onDropcovers this. - Expecting
*to work on any wrapper. The*operator works on a custom type only if it implementsDeref. Without that, the compiler reports that the type cannot be dereferenced.
Exercise
A Vec<i32> is 24 bytes on a 64-bit machine, while &Vec<i32> is 8 bytes. Using the ideas in this chapter, explain why the sizes differ and which of the two is a smart pointer.
Show answer
Vec<i32> is the smart pointer. It owns a heap buffer and stores an address, a length, and a capacity, which add up to 24 bytes. It frees the buffer through Drop when it goes out of scope. &Vec<i32> is a plain reference. It only holds the address of the Vec, which is 8 bytes, and it owns nothing and frees nothing.
Exercise
In the Tracked example, suppose main creates let a = Tracked { value: 1, label: "a" }; and then let b = Tracked { value: 2, label: "b" };, and nothing else. In what order do the two "releasing" lines print, and why?
Show answer
It prints "releasing b" and then "releasing a". Rust drops local variables in the reverse order of their declaration when the scope ends, so the most recently created value is released first.