Rust Reference ยท Smart Pointers and Memory
Rust Weak<T> type
Reference for Rust Weak<T> from std::rc and std::sync: downgrade, upgrade, counts, Weak::new and how weak pointers break reference cycles.
Weak<T> is a pointer to a value owned by Rc<T> (or Arc<T>) that does not keep the value alive. It exists in two flavors: std::rc::Weak for Rc, and std::sync::Weak for Arc. Both work the same way.
A Weak can be turned back into an owning pointer with upgrade(), which returns Some(Rc<T>) while at least one strong owner remains and None after the value has been dropped. This makes Weak the right tool for back-references: a child pointing at its parent, a cache that must not keep entries alive, an observer list that should not own its observers.
use std::rc::{Rc, Weak}; let strong = Rc::new(1); let weak: Weak<i32> = Rc::downgrade(&strong); assert_eq!(weak.upgrade().map(|rc| *rc), Some(1));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> Weak<T> { pub const fn new() -> Weak<T>; } impl<T: ?Sized> Weak<T> { pub fn upgrade(&self) -> Option<Rc<T>>; pub fn strong_count(&self) -> usize; pub fn weak_count(&self) -> usize; pub fn ptr_eq(&self, other: &Weak<T>) -> bool; }
| Item | Description |
|---|---|
Rc::downgrade(&rc) |
Creates a Weak and increments the weak count. |
Weak::new() |
A Weak that points to nothing and allocates nothing; upgrade always returns None. |
weak.upgrade() |
Some(Rc<T>) with a new strong owner, or None if the value was dropped. |
strong_count() |
Current number of strong owners (0 once dropped). |
weak_count() |
Number of Weak pointers while the value is alive; 0 after it is dropped. |
Edge cases. upgrade returns an Option, never panics. Dropping the last strong pointer drops the value immediately, but the memory block stays allocated until the last Weak is also gone. Weak<T> implements Clone and Default (the same as Weak::new).
Usage notes
- Store the parent link as
RefCell<Weak<Node>>so it can be set after the parent exists, as in the example above. - Never hold the upgraded
Rclonger than needed: while it exists, it keeps the value alive again. - A cache of
Weakpointers needs periodic cleanup, because dead entries remain in the map asWeakshells. Weakis notSendforrc::Weak; usesync::WeakwithArcacross threads.sync::Weak::upgradeis atomic and safe to race with the last strong drop.Rc::new_cyclic(|weak| ...)builds a value that already knows aWeakto itself.Weakhas noDeref: you mustupgrade()before using the value.
Related
- Rc, Arc, RefCell
- Tutorial: Rc and Arc, Smart pointers overview