Answer#
C++ code often reaches for std::shared_ptr by habit, because ownership is hard to see. Port with the question "who owns this?" first. In Rust most values have one obvious owner, and the other users borrow with &T or &mut T, so a large part of the shared_ptr uses turn into plain values and references.
| C++ | Rust | Notes |
|---|---|---|
std::unique_ptr<T> | Box<T> or just T | Box for heap allocation, recursive types and trait objects |
std::shared_ptr<T> (one thread) | Rc<T> | Counts owners; read-only access |
std::shared_ptr<T> (several threads) | Arc<T> | Same with an atomic counter |
std::weak_ptr<T> | Weak<T> | upgrade() gives Option<Rc<T>> |
shared_ptr<T> with mutation | Rc<RefCell<T>>, Arc<Mutex<T>> | The cell or lock is part of the type |
raw T* that does not own | &T, &mut T | Checked by the compiler |
The program shows each of them, with the counts printed. It was compiled and run with rustc 1.93.0.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
use std::sync::Arc;
struct Owner {
name: String,
gadgets: RefCell<Vec<Weak<Gadget>>>,
}
struct Gadget {
id: u32,
owner: Rc<Owner>,
}
fn main() {
// std::unique_ptr<T> -> Box<T>
let b = Box::new(5);
println!("{}", *b + 1);
// std::shared_ptr<T> -> Rc<T> (one thread) or Arc<T> (shared between threads); counts are visible
let a = Rc::new(String::from("shared"));
let a2 = Rc::clone(&a);
println!("rc strong = {}", Rc::strong_count(&a));
drop(a2);
println!("rc strong = {}", Rc::strong_count(&a));
let arc = Arc::new(7);
let t = { let arc = Arc::clone(&arc); std::thread::spawn(move || *arc * 2) };
println!("arc: {} {}", t.join().unwrap(), Arc::strong_count(&arc));
// std::weak_ptr<T> -> Weak<T>, used for the "back" link so that there is no cycle
let owner = Rc::new(Owner { name: "Ada".into(), gadgets: RefCell::new(vec![]) });
let g = Rc::new(Gadget { id: 1, owner: Rc::clone(&owner) });
owner.gadgets.borrow_mut().push(Rc::downgrade(&g));
println!("{} owns {} gadget(s); gadget {} belongs to {}", owner.name, owner.gadgets.borrow().len(), g.id, g.owner.name);
println!("owner strong={} weak={}", Rc::strong_count(&owner), Rc::weak_count(&owner));
drop(g);
println!("after drop: upgrade -> {}", owner.gadgets.borrow()[0].upgrade().is_none());
}6
rc strong = 2
rc strong = 1
arc: 14 1
Ada owns 1 gadget(s); gadget 1 belongs to Ada
owner strong=2 weak=0
after drop: upgrade -> trueReading the output: cloning an Rc raises the strong count and dropping the clone lowers it; the Arc is back to 1 after the thread finished and dropped its clone. The owner's strong count is 2 because the variable owner and the gadget's owner field both hold it, while the owner keeps only a Weak pointer to the gadget. So when g, the gadget's last strong handle, is dropped, the gadget is freed, upgrade() on the weak pointer returns None (the last line prints true), and no cycle keeps anything alive.
How to do it#
- For each
unique_ptrmember, check if the member can simply be a value (T) or aVec<T>. UseBox<T>only when you need an indirection: a recursive type, a very large value, or a trait object (Box<dyn Trait>). - For each
shared_ptr, find the real owner. If one exists, port to a reference or an id (see the thread on parent pointers and arenas). If sharing is real, useRc(one thread) orArc(several). - If the shared data changes, add the cell or lock inside:
Rc<RefCell<T>>checks borrows at run time and panics on a conflict;Arc<Mutex<T>>makes other threads wait. - Keep back links
Weak, as the code above does withgadgets.
Common mistakes#
- Using
Arc<Mutex<T>>everywhere "to be safe". It works, but it hides who owns what, and lock contention appears under load. - Using
Rcin code that later moves to threads. The compiler error (Rc<..>cannot be sent between threads safely) is the fix prompt: switch toArc. - Making reference cycles with
Rcon both sides. They are never freed (see the thread on memory leaks).
Related questions#
Is Arc::clone expensive?#
It increments an atomic counter, which is cheap but not free, and costs more when many threads touch it. Clone it once per task, not once per item.
Where is make_shared?#
Rc::new and Arc::new.
Sources#
- The Rust Book, "Smart Pointers": https://doc.rust-lang.org/book/ch15-00-smart-pointers.html
std::rc: https://doc.rust-lang.org/std/rc/index.htmlstd::sync::Arc: https://doc.rust-lang.org/std/sync/struct.Arc.html