Smart Pointer (Rust)

A smart pointer is a type that acts like a pointer but adds extra capabilities — heap allocation, reference counting, or interior mutability — and automatically cleans up its data when dropped.

Rust

Plain references (&T) only borrow. Smart pointers own their data and add behavior. The key ones in std are Box<T> (heap allocation, single owner), Rc<T>/Arc<T> (shared ownership), and RefCell<T>/Mutex<T> (interior mutability with runtime-checked borrows).

What makes them 'smart' is that they implement the Deref trait, so you can use them like ordinary references, and the Drop trait, so cleanup runs automatically when they leave scope. This is RAII: resource lifetimes follow ownership with no manual free.

You compose smart pointers to get the exact semantics you need: Rc<RefCell<T>> for shared mutable single-threaded data, Arc<Mutex<T>> for shared mutable data across threads. Choosing the right combination is a core Rust design skill.

Examples

Rust

use std::rc::Rc;
use std::cell::RefCell;

fn main() {
    let shared = Rc::new(RefCell::new(0));
    let clone = Rc::clone(&shared);
    *clone.borrow_mut() += 7;
    println!("{}", shared.borrow());
}

Output:

7

Learn it in a lesson

See also

Back to the Dictionary