Sub topic 9
Rc<T>: several owners for one value
This chapter assumes you know Rust ownership and moves, borrowing rules, and basic traits and generics. It also assumes you have met Box<T> and the Deref and Drop traits from earlier chapters.
The problem: one owner is not always enough
Rust normally gives each value exactly one owner. When the owner goes out of scope, the value is dropped. That rule breaks down for some data. In a graph, several edges can point to the same node. The node must stay alive until the last edge is gone, and you can't know at compile time which edge that is.
Rc<T> solves this. It stands for reference counted. An Rc<T> owns a value on the heap and keeps a count of how many Rc handles point to it. Each new handle raises the count. Each dropped handle lowers it. When the count reaches zero, the value is dropped.
Cloning a handle, not the data
Call Rc::clone(&a) to create another owner. This copies a pointer and adds one to the count. It does not copy the data. The convention is to write Rc::clone(&a) instead of a.clone(), so a cheap count increment is easy to tell apart from a deep copy.
use std::rc::Rc;
fn main() {
let a = Rc::new(String::from("shared"));
println!("count after creating a = {}", Rc::strong_count(&a));
let _b = Rc::clone(&a);
println!("count after creating b = {}", Rc::strong_count(&a));
{
let _c = Rc::clone(&a);
println!("count after creating c = {}", Rc::strong_count(&a));
}
println!("count after c goes out of scope = {}", Rc::strong_count(&a));
}The program prints counts of 1, 2, 3, and then 2. When _c leaves its inner scope, its Drop implementation lowers the count. The string is freed only when the last handle goes away.
What you can do with an Rc
Rc<T> implements Deref, so you can call methods of T through it, such as a.len() on an Rc<String>. Because Rc<T> gives out only shared references, you can read the value but you can't mutate it. Allowing several mutable owners would break the borrowing rules. Chapters on RefCell<T> show how to add mutation safely.
Common errors
- Using
Rcacross threads.Rc<T>is notSend, because its count is updated without atomic operations. Sending one to another thread is a compile error. UseArc<T>for that case, covered later. - Expecting to mutate.
*a = ...ora.push(...)fails to compile on anRc<Vec<T>>.Rc::get_mutworks only when the count is exactly 1. - Cloning the data by accident.
a.clone()on anRcis still the cheap handle clone. But calling(*a).clone()copies the inner value. - Reference cycles. If two
Rcvalues point to each other, the counts never reach zero and the memory leaks. A later chapter fixes this withWeak<T>.
Exercise
In the example above, what is the strong count after _c goes out of scope, and why can't you push to an Rc<Vec<i32>>?
Show answer
The count is 2, because dropping _c decrements it and a and _b remain. You can't push because Rc<T> only hands out shared references, and push needs &mut Vec<i32>.