Rc

当需要多重所有权时,可以使用Rc(引用计数)。Rc 会跟踪引用的数量,这意味着 Rc 内部包裹的值的所有者数量。

每当克隆一个 Rc 时,Rc 的引用计数增加 1,每当一个克隆的 Rc 超出作用域被丢弃时,引用计数减少 1。当 Rc 的引用计数变为零时(这意味着没有剩余的所有者),Rc 和该值都会被丢弃。

克隆 Rc 永远不会执行深拷贝。克隆只是创建另一个指向被包裹值的指针,并递增计数。

use std::rc::Rc;

fn main() {
    let rc_examples = "Rc examples".to_string();
    {
        println!("--- rc_a is created ---");
        
        let rc_a: Rc<String> = Rc::new(rc_examples);
        println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a));
        
        {
            println!("--- rc_a is cloned to rc_b ---");
            
            let rc_b: Rc<String> = Rc::clone(&rc_a);
            println!("Reference Count of rc_b: {}", Rc::strong_count(&rc_b));
            println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a));
            
            // Two `Rc`s are equal if their inner values are equal
            println!("rc_a and rc_b are equal: {}", rc_a.eq(&rc_b));
            
            // We can use methods of a value directly
            println!("Length of the value inside rc_a: {}", rc_a.len());
            println!("Value of rc_b: {}", rc_b);
            
            println!("--- rc_b is dropped out of scope ---");
        }
        
        println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a));
        
        println!("--- rc_a is dropped out of scope ---");
    }
    
    // Error! `rc_examples` already moved into `rc_a`
    // And when `rc_a` is dropped, `rc_examples` is dropped together
    // println!("rc_examples: {}", rc_examples);
    // TODO ^ Try uncommenting this line
}

另请参阅

std::rcstd::sync::arc