Progrust Library.

// dictionary

Rc<T> (Reference Counting).

Rc

Rc<T> (Reference Counted) は、複数の所有者が同じ値を共有する場合に使用するスマートポインタです。参照カウントにより、最後の所有者がスコープを抜ける時に自動的にメモリが解放されます。

基本的な例

use std::rc::Rc;

fn main() {
    let a = Rc::new(5);
    let b = Rc::clone(&a);  // 参照カウント: 2
    let c = Rc::clone(&a);  // 参照カウント: 3
    
    println!("参照カウント: {}", Rc::strong_count(&a));  // 3
}

グラフ構造の表現

use std::rc::Rc;
use std::cell::RefCell;

#[derive(Debug)]
struct Node {
    value: i32,
    children: Vec<Rc<RefCell<Node>>>,
}
なぜRcなのか?

グラフでは複数の親が同じ子ノードを参照することがあります。Rc はそのような共有所有権を実現します。

内部可変性が必要な場合は RefCell<T> と組み合わせます。

スレッドセーフなバージョンは Arc<T> (Atomic Reference Counting) を参照してください。

この辞書が使われているページ

backlinks 4

  1. 辞書Arc<T> (Atomic Reference Counting)
  2. 辞書Box
  3. 辞書RefCell<T>
  4. 辞書ジェネリクス(Generics)