Rust 智能指針(Rc)


std::rc::Rc

Rc代表引用計數

以下是標准庫文檔的介紹

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.

總結為以下幾點:

  • 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));
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM