Smart pointers help manage memory safely by automatically cleaning up when no longer needed. They keep track of who owns data so you don't have to worry about mistakes.
0
0
Ownership with smart pointers in Rust
Introduction
When you want to share data between parts of your program without copying it.
When you need to have multiple owners of the same data safely.
When you want to store data on the heap but still have automatic cleanup.
When you want to mutate data even if multiple owners exist.
When you want to avoid manual memory management and prevent bugs.
Syntax
Rust
let smart_pointer = SmartPointerType::new(data);Common smart pointers in Rust include Box, Rc, and RefCell.
Box owns data uniquely on the heap, Rc allows multiple owners, and RefCell allows mutation inside immutable owners.
Examples
Box stores the value 5 on the heap with unique ownership.Rust
let b = Box::new(5);
Rc allows multiple owners of the value 10 by cloning the pointer, not the data.Rust
use std::rc::Rc; let rc1 = Rc::new(10); let rc2 = Rc::clone(&rc1);
RefCell allows changing data even if the owner is immutable.Rust
use std::cell::RefCell; let data = RefCell::new(7); *data.borrow_mut() += 1;
Sample Program
This program shows how Rc smart pointer allows multiple owners of the same string. It prints the number of owners and the values.
Rust
use std::rc::Rc;
fn main() {
let a = Rc::new(String::from("hello"));
let b = Rc::clone(&a);
let c = Rc::clone(&a);
println!("Count after clones: {}", Rc::strong_count(&a));
println!("a: {}, b: {}, c: {}", a, b, c);
}OutputSuccess
Important Notes
Smart pointers automatically free memory when no owners remain.
Using Rc is for shared ownership but is not thread-safe; use Arc for threads.
RefCell allows mutation checked at runtime, so be careful to avoid borrow errors.
Summary
Smart pointers manage ownership and memory safely.
Box for unique ownership, Rc for shared ownership, RefCell for interior mutability.
They help prevent bugs by automating cleanup and enforcing rules.