std::rc::Rc
Rc 代表引用計(jì)數(shù)
以下是標(biāo)準(zhǔn)庫(kù)文檔的介紹 Single-threaded reference-counting pointers. 'Rc’ stands for 'Reference Counted’. The type Rc provides 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.
總結(jié)為以下幾點(diǎn): + Rc 讓一個(gè)值有多個(gè)所有者,調(diào)用clone 產(chǎn)生一個(gè)指針指向該值 + 當(dāng)Rc 指針全部銷(xiāo)毀時(shí),該值也銷(xiāo)毀 + 不能通過(guò)Rc 獲得可變引用 + Rc 是非原子引用,只能用于單線(xiàn)程,多線(xiàn)程用Arc use std::rc::Rc;
fn main() {
let five = Rc::new(5);
let five1 = five.clone();
//Rc實(shí)現(xiàn)了Deref trait,可以自動(dòng)解引用,因此下面打印成功
println!("{}", five1);
//可以通過(guò)調(diào)用strong_count查看引用計(jì)數(shù)
println!("{}", Rc::strong_count(&five1));
} 順便介紹一下rc::Weak 標(biāo)準(zhǔn)庫(kù)介紹 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. 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 用于不擁有所有權(quán)的引用,通過(guò)調(diào)用upgrade 調(diào)用值,這個(gè)方法返回一個(gè)Optical<Rc<T>>
Weak 不能阻止值被丟棄,當(dāng)值被丟棄時(shí),調(diào)用upgrade 時(shí)返回None
使用Weak 可以避免Rc 的循環(huán)引用 調(diào)用Rc::downgrade 來(lái)獲得一個(gè)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));
}
|