std::rc::Rc
Rc
代表引用計數
以下是標准庫文檔的介紹
Single-threaded reference-counting pointers. 'Rc' stands for 'Reference Counted'.
The type Rcprovides shared ownership of a value of type T, allocated in the heap. Invoking clone on Rc produces a new pointer to the same value in the heap.
When the last Rc pointer to a given value is destroyed, the pointed-to value is also destroyed.
Shared references in Rust disallow mutation by default, and Rc is no exception: you cannot generally obtain a mutable reference to something inside an Rc. If you need mutability, put a Cell or RefCell inside the Rc; see an example of mutability inside an Rc.
Rc uses non-atomic reference counting. This means that overhead is very low, but an Rc cannot be sent between threads, and consequently Rc does not implement Send. As a result, the Rust compiler will check at compile time that you are not sending Rcs between threads. If you need multi-threaded, atomic reference counting, use sync::Arc.
總結為以下幾點:
Rc
讓一個值有多個所有者,調用clone
產生一個指針指向該值- 當
Rc
指針全部銷毀時,該值也銷毀 - 不能通過
Rc
獲得可變引用 Rc
是非原子引用,只能用於單線程,多線程用Arc
use std::rc::Rc;
fn main() {
let five = Rc::new(5);
let five1 = five.clone();
//Rc實現了Deref trait,可以自動解引用,因此下面打印成功
println!("{}", five1);
//可以通過調用strong_count查看引用計數
println!("{}", Rc::strong_count(&five1));
}
順便介紹一下rc::Weak
標准庫介紹
Weak is a version of Rc that holds a non-owning reference to the managed value. The value is accessed by calling upgrade on the Weak pointer, which returns an Option<Rc
>.
Since a Weak reference does not count towards ownership, it will not prevent the inner value from being dropped, and Weak itself makes no guarantees about the value still being present and may return None when upgraded.
A Weak pointer is useful for keeping a temporary reference to the value within Rc without extending its lifetime. It is also used to prevent circular references between Rc pointers, since mutual owning references would never allow either Rc to be dropped. For example, a tree could have strong Rc pointers from parent nodes to children, and Weak pointers from children back to their parents.
The typical way to obtain a Weak pointer is to call Rc::downgrade.
Weak
用於不擁有所有權的引用,通過調用upgrade
調用值,這個方法返回一個Optical<Rc<T>>
Weak
不能阻止值被丟棄,當值被丟棄時,調用upgrade
時返回None
- 使用
Weak
可以避免Rc
的循環引用 - 調用
Rc::downgrade
來獲得一個Weak
指針
use std::rc::Rc;
fn main() {
let five = Rc::new(5);
let weak_five = Rc::downgrade(&five);
let strong_five: Option<Rc<_>> = weak_five.upgrade();
println!("{}", strong_five.unwrap());
println!("weak: {}, strong: {}", Rc::weak_count(&five), Rc::strong_count(&five));
}