Sub topic 15
Weak<T>: non-owning references that break cycles
This chapter assumes you know Rc<T>, RefCell<T>, and the combination Rc<RefCell<T>>. It also assumes you have seen how a reference cycle leaks memory. Here you will learn how Weak<T> lets one side of a link point at a value without owning it.
Why a cycle needs a non-owning link
Rc<T> frees its value when the strong count reaches zero. If two values hold Rc handles to each other, neither count can reach zero, and neither value is ever dropped. Rust treats this as a leak, not as unsafe code, so the compiler accepts it.
The usual cause is a data structure with links in both directions, such as a tree where a parent owns its children and each child also wants to reach its parent. The fix is to decide which direction means ownership. The other direction becomes a Weak<T>.
A Weak<T> is a pointer to the same allocation as an Rc<T>, but it does not keep the value alive. It only keeps a small bookkeeping record alive, so it can later find out whether the value still exists.
Strong count and weak count
Every Rc allocation tracks two numbers:
- The strong count is the number of
Rc<T>handles. When it reaches zero, the value is dropped. - The weak count is the number of
Weak<T>handles. It has no effect on when the value is dropped.
The memory block that holds the two counters is freed only when both counts reach zero. This is why a Weak can safely ask "are you still there?" after the value is gone.
| Operation | Effect on strong count | Effect on weak count |
|---|---|---|
| `Rc::new(v)` | starts at 1 | starts at 0 |
| `Rc::clone(&rc)` | +1 | none |
| `Rc::downgrade(&rc)` | none | +1 |
| `Weak::clone(&weak)` | none | +1 |
| `weak.upgrade()` returning `Some(rc)` | +1 while the new `Rc` lives | none |
| Dropping an `Rc` | -1 | none |
| Dropping a `Weak` | none | -1 |
Creating and upgrading a Weak
You create a Weak from an existing Rc with Rc::downgrade(&rc). You cannot read the value through a Weak directly, because the value might already be gone. Instead you call upgrade(), which returns Option<Rc<T>>:
Some(rc)if the value is still alive. You get a fresh strong handle, so the value cannot disappear while you use it.Noneif the strong count has already reached zero.
Weak::new() creates a Weak that points at nothing. Its upgrade() always returns None. This is useful as an initial value before a real parent exists.
A tree with parent links
The tree below gives each node a list of children it owns and a link to its parent that it does not own. The parent link is wrapped in RefCell because it must be set after the child already exists and is shared.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Node {
value: i32,
parent: RefCell<Weak<Node>>,
children: RefCell<Vec<Rc<Node>>>,
}
fn main() {
let leaf = Rc::new(Node {
value: 3,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![]),
});
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.value));
let branch = Rc::new(Node {
value: 5,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![Rc::clone(&leaf)]),
});
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.value));
println!(
"branch strong = {}, weak = {}",
Rc::strong_count(&branch),
Rc::weak_count(&branch)
);
}The program prints:
leaf parent = None
leaf parent = Some(5)
branch strong = 1, weak = 1The first line prints None because Weak::new() points at nothing. After Rc::downgrade(&branch), the leaf can reach the branch, so the second line prints Some(5). The branch has one strong handle (the variable branch) and one weak handle (inside leaf). Because the leaf's link is weak, dropping branch frees it.
Watching the value disappear
The next program shows the counts change as the parent goes out of scope. It also shows that the child survives its parent, because the parent never owned the child's allocation exclusively. The child is owned by leaf itself.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Node {
value: i32,
parent: RefCell<Weak<Node>>,
children: RefCell<Vec<Rc<Node>>>,
}
fn main() {
let leaf = Rc::new(Node {
value: 3,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![]),
});
{
let branch = Rc::new(Node {
value: 5,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![Rc::clone(&leaf)]),
});
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);
println!(
"branch strong = {}, weak = {}",
Rc::strong_count(&branch),
Rc::weak_count(&branch)
);
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf)
);
}
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.value));
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf)
);
}The program prints:
branch strong = 1, weak = 1
leaf strong = 2, weak = 0
leaf parent = None
leaf strong = 1, weak = 0While the inner scope is active, the leaf has two strong owners: the leaf variable and the branch's children vector. When the scope ends, branch is dropped because its strong count hits zero. Dropping it also drops its children vector, which releases one strong handle on the leaf. Afterwards upgrade() on the leaf's parent link returns None, and the leaf's strong count is back to 1.
Choosing the direction of the link
Which side should be weak? Ask which value logically controls the other's lifetime.
- In a tree, parents own children, so parent-to-child links are
Rcand child-to-parent links areWeak. - In an observer pattern, the subject usually holds
Weakreferences to observers, so a forgotten observer does not stay alive forever. - In a cache, entries can be held as
Weakso the cache never keeps values alive by itself. - In a doubly linked list, forward links are
Rcand backward links areWeak.
If you can't name an owner, the design may have a cycle that needs rethinking, not just a Weak bolted on.
Common errors and gotchas
- Forgetting to handle
None. Calling.upgrade().unwrap()panics if the target is gone. Preferif let Some(parent) = weak.upgrade()ormatchunless you can prove the value is alive. - Holding an upgraded
Rctoo long. AnRcobtained fromupgrade()is a strong handle. If you store it in a long-lived structure, you have rebuilt the strong link and may recreate the cycle. - Mutating with a live borrow. The parent field above is a
RefCell. Writing to it withborrow_mut()while anotherborrow()of the same field is alive panics at runtime, as covered in theRefCellchapter. Keep borrows short. - Expecting weak counts to block drops. A nonzero weak count never delays dropping the value. It only delays freeing the counter block.
- Assuming
Weakis thread-safe.std::rc::Weakis single-threaded, likeRc. Across threads, usestd::sync::WeakwithArc.
Exercise
A Rc<Node> named a has strong count 1 and weak count 0. You run let w = Rc::downgrade(&a); then let b = w.upgrade().unwrap();. What are the strong and weak counts of a after those two lines? If you then run drop(a); drop(b);, what does w.upgrade() return?
Show answer
After the two lines, the strong count is 2 (the original a plus the upgraded b) and the weak count is 1 (w). After drop(a) and drop(b), the strong count reaches 0, so the value is dropped and w.upgrade() returns None.
Exercise
A tree node stores parent: RefCell<Rc<Node>> and each parent stores its children in Vec<Rc<Node>>. Why does this leak, and what one-type change fixes it?
Show answer
Parent and child each hold a strong handle to the other, so neither strong count can reach zero and neither node is ever dropped. Changing the parent field to RefCell<Weak<Node>> makes the child-to-parent link non-owning, which lets the parent be dropped when its last outside owner goes away.