liveBook · Manning

Smart pointer

As explained in Rust in Action: Systems programming concepts and techniques

A smart pointer is a pointer-like data structure that provides additional capabilities such as ownership management, reference counting, or synchronization.

A smart pointer behaves like a pointer but does more than hold a memory address. In Rust, smart pointers offer safer, feature-rich alternatives to raw pointers, which are unsafe to use. They often wrap a raw pointer and add rules or capabilities for working with the data it points to. section 6.2.2

Choose a type for the capability you need:

  • Box<T> is a programmer-facing pointer type built on lower-level pointer machinery. section 6.2.3
  • Rc<T> and Arc<T> support shared access. For deeply interlinked data, Weak pointers allow access without increasing the reference count, helping prevent cycles. section 6.2.3
  • Cell<T> and RefCell<T> provide interior mutability. A combination such as Rc<RefCell<T>> trades runtime cost for the flexibility of mutation alongside shared ownership. section 6.2.2

Compare a reference and a box

Put an array behind a reference, then put another behind a Box<[u8]>. Print each value’s location, size, and pointed-to address. In the illustrated run, the reference occupies 8 bytes and the box occupies 16 bytes: pointer-like values need not have the same layout. Added capabilities can cost space and runtime work. section 6.2 section 6.5

These types are extensible: lower-level components in Rust’s core and allocation modules can serve as starting points for a new smart pointer. Building a safe one in full requires further Rust internals. section 6.2.3

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Defines smart pointers, compares their capabilities, and names construction primitives, but defers a full account of building safe pointer types.
Examples
Compares the addresses and sizes of a reference and Box<[u8]>, and combines Rc<T> with RefCell<T>.
What it assumes
Starts without assuming prior knowledge of pointers or memory, while leaving some advanced Rust internals for later investigation.
What you can do after
Evaluate/understand which named Rust pointer types offer shared access, interior mutability, or weak access, and what costs added features bring.
How it connects
Connects smart pointers to raw pointers, shared ownership, reference counting, interior mutability, and memory layout.

Also explained in

Compare how 5 books explain smart pointer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.