Sub topic 16
Rc: Multiple Owners
This chapter assumes you know the three ownership rules, moves, shared references, and Box. Single ownership covers most programs. Sometimes, though, several parts of a program need to own the same data, and no single owner is the obvious one to free it. Rc<T> handles that case.
What Rc does
Rc<T> is a reference-counted pointer. It stores a value of type T on the heap, along with a count of how many Rc handles point to it. Cloning an Rc doesn't copy the data. It adds one to the count and returns a new handle. When a handle is dropped, the count goes down by one. When the count reaches zero, the value is dropped.
This keeps the ownership model intact. The last owner to go away is the one that frees the data, and that moment is decided at run time instead of at compile time.
Sharing a value
use std::rc::Rc;
fn main() {
let a = Rc::new(String::from("shared text"));
println!("count after a: {}", Rc::strong_count(&a));
let b = Rc::clone(&a);
println!("count after b: {}", Rc::strong_count(&a));
{
let c = Rc::clone(&a);
println!("count after c: {} ({c})", Rc::strong_count(&a));
}
println!("count after c leaves scope: {}", Rc::strong_count(&a));
println!("{a} / {b}");
}This prints counts of 1, 2, 3, and then 2 again once c leaves its inner scope. Write Rc::clone(&a) instead of a.clone(). Both work, but the first form shows readers that you're making a cheap handle and not a deep copy.
What you can and cannot do
An Rc<T> gives you shared read access only. You can read through any handle, but you can't get a &mut T from one while other handles exist. That restriction is what keeps the borrowing rules sound. To mutate shared data, pair Rc with RefCell, which the next chapter covers.
Rc isn't thread-safe. Its count is updated without atomic operations, so the compiler refuses to let you send an Rc to another thread. Use Arc for that, which a later chapter covers.
Common errors
- Using
Rcwhen a plain reference would do. If one owner clearly outlives the others, borrow from it. Reach forRconly when no owner is obviously last. - Trying to mutate through an
Rc. Code like*a = ...fails to compile because the value is shared. - Reference cycles. If two
Rcvalues point at each other, their counts never reach zero and the memory leaks. Rust treats leaks as safe, so the compiler won't stop you.Weak<T>is the standard tool for breaking such cycles. - Expecting
Rc::cloneto be free. It's cheap, but it still changes a counter.
Exercise
You write let b = Rc::clone(&a); and later call Rc::strong_count(&a). If a was the only handle before the clone, what does the call return, and does the string data get copied?
Show answer
It returns 2. The string data is not copied. Only the reference count increases, and both handles point to the same heap allocation.
Exercise
Why does the compiler reject sending an Rc<String> to another thread with thread::spawn, and which type should you use instead?
Show answer
Rc updates its count with non-atomic operations, so two threads could corrupt the count. It doesn't implement Send. Use Arc, which uses atomic counting.