Sub topic 16
Rc: multiple owners
This chapter assumes you know the three ownership rules, moves, shared references, and Box<T>. It does not require RefCell, which the next chapter covers. We use it only once, in the last example.
Why single ownership is sometimes too strict
Every value has exactly one owner. That model works until the data really has several owners. Two graph edges can point at the same node. Two lists can share one tail. Several widgets can hold the same configuration. No single owner can be named, because the value should live as long as the last user needs it.
References don't solve this. A reference borrows from an owner that must outlive it, and here no owner outlives all the users. Rc<T> (reference counted) solves it by moving the "who frees it" decision to run time. The value lives on the heap with a counter beside it. Each owner increments the counter when it is created and decrements it when it is dropped. When the counter reaches zero, the value is dropped.
Creating and cloning an Rc
Rc::new(value) moves the value to the heap and returns an Rc<T> with a strong count of 1. Rc::clone(&rc) returns another pointer to the same allocation and increments the count. It does not copy the data.
use std::rc::Rc;
struct Gadget {
id: u32,
owner: Rc<String>,
}
fn main() {
let owner = Rc::new(String::from("Gizmo"));
let g1 = Gadget { id: 1, owner: Rc::clone(&owner) };
let g2 = Gadget { id: 2, owner: Rc::clone(&owner) };
println!("count = {}", Rc::strong_count(&owner));
drop(owner);
println!("gadget {} owned by {}", g1.id, g1.owner);
println!("gadget {} owned by {}", g2.id, g2.owner);
println!("count = {}", Rc::strong_count(&g1.owner));
}This prints count = 3, then the two owner lines, then count = 2. Dropping the original owner binding doesn't free the string, because the two gadgets still hold it. The string is freed only when g1 and g2 are both gone.
Writing Rc::clone(&owner) rather than owner.clone() is the usual convention. Both compile to the same thing. The function-call form makes it obvious in a code review that you are bumping a counter and not performing a deep copy.
What Rc gives you, and what it doesn't
Rc<T> implements Deref<Target = T>, so you can call T's methods and read through it directly. It gives you shared access only. You cannot get a &mut T out of an Rc<T> when other owners might exist, because that would break the rule against mutating aliased data.
use std::rc::Rc;
fn main() {
let a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
// a.push(4); // error[E0596]: cannot borrow data in an `Rc` as mutable
println!("{} {}", a.len(), b.len());
}If you need mutation you have three options.
- Use
Rc::get_mut(&mut rc). It returnsSome(&mut T)only when the strong count is 1 (and noWeakpointers exist), andNoneotherwise. - Use
Rc::make_mut(&mut rc). It clones the inner value first if the count is above 1 (a copy-on-write approach), so the other owners keep seeing the old data. - Put a
RefCell<T>inside theRcfor run-time-checked mutation, as shown in the next chapter.
use std::rc::Rc;
fn main() {
let mut a = Rc::new(vec![1, 2, 3]);
println!("{}", Rc::get_mut(&mut a).is_some()); // true: only one owner
let b = Rc::clone(&a);
println!("{}", Rc::get_mut(&mut a).is_some()); // false: shared
Rc::make_mut(&mut a).push(4); // clones the vector because it is shared
println!("{:?} {:?}", a, b);
println!("{}", Rc::ptr_eq(&a, &b));
}The output is true, false, [1, 2, 3, 4] [1, 2, 3], then false. After make_mut, a points to a new allocation and b still points to the old one. Rc::ptr_eq compares allocation addresses, not contents.
Rc is not thread-safe
The counter in Rc is updated with ordinary, non-atomic operations. Two threads incrementing it at once could corrupt it. The compiler therefore marks Rc<T> as neither Send nor Sync, and it refuses to compile code that sends one to another thread:
error[E0277]: `Rc<i32>` cannot be sent between threads safelyThe fix is Arc<T>, which uses atomic counters. It has the same API and costs slightly more per clone. Use Rc when everything stays on one thread, and Arc as soon as threads are involved.
Reference cycles and Weak
Reference counting has a known weakness. If A holds an Rc to B and B holds an Rc to A, neither count can reach zero. The memory leaks. Rust treats leaks as safe, so the compiler won't stop you.
The remedy is Weak<T>, a non-owning pointer. Rc::downgrade(&rc) creates one. It increments the weak count but not the strong count, and it doesn't keep the value alive. To use it, call .upgrade(). That returns Some(Rc<T>) if the value still exists and None if it has been dropped.
A common pattern is a tree in which parents own children strongly and children point to parents weakly:
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Node {
value: i32,
parent: RefCell<Weak<Node>>,
}
fn main() {
let leaf = Rc::new(Node {
value: 3,
parent: RefCell::new(Weak::new()),
});
println!("parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.value));
let branch = Rc::new(Node {
value: 5,
parent: RefCell::new(Weak::new()),
});
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);
println!("parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.value));
println!(
"strong = {}, weak = {}",
Rc::strong_count(&branch),
Rc::weak_count(&branch)
);
}The output is parent = None, parent = Some(5), then strong = 1, weak = 1. The RefCell is there only so the parent link can be set after leaf is created. The next chapter explains it.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Expecting `Rc::clone` to copy the data | Surprise that a change seen through one handle shows up in another | Remember that it copies the pointer. Use `(*rc).clone()` or `make_mut` for a real copy. |
| Mutating through `Rc<T>` | E0596, cannot borrow as mutable | Use `Rc<RefCell<T>>`, `get_mut`, or `make_mut` |
| Moving an `Rc` into `thread::spawn` | E0277, not `Send` | Switch to `Arc` |
| Strong pointers in both directions | Memory never freed, `Drop` never runs | Make the back-pointer a `Weak` |
| Using `Rc` where a reference would do | Needless counting and heap allocation | Prefer `&T` if one owner clearly outlives the users |
Choosing Rc
Reach for Rc when the value has several owners and you can't say in advance which one lives longest. If one owner outlives all users, a plain reference is simpler and has no run-time cost. If you only need to move a value around, a move is enough. Rc costs one extra heap allocation for the counters, plus an increment and decrement on each clone and drop. That cost is small but not zero.
Exercise
A program stores one configuration object in an Rc<Config>, then clones the Rc into three components. After drop is called on the original handle, what is Rc::strong_count on one component's handle, and when is the Config freed?
Show answer
The count is 3. There were four handles, and dropping the original removed one. The Config is freed when the last of the three component handles is dropped, which takes the count to 0. Dropping the original handle does not free anything because other owners remain.
Exercise
Two structs, Parent and Child, each hold an Rc to the other. Both variables go out of scope at the end of main. Does either Drop implementation run? How do you fix it?
Show answer
Neither runs. Each strong count stays at 1 after the variables go out of scope, because each value is still owned by the other, so the memory leaks. Change one direction, normally the child's link to its parent, to a Weak created with Rc::downgrade. Then only the parent-to-child link counts as strong, and the counts can reach zero.