Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rc

Коли потрібне множинне володіння, можна використовувати Rc(Reference Counting). Rc відстежує кількість посилань, що означає кількість власників значення, загорнутого всередину Rc.

Лічильник посилань Rc збільшується на 1 щоразу, коли Rc клонують, і зменшується на 1 щоразу, коли один клонований Rc виходить з області видимості. Коли лічильник посилань 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::rc і std::sync::arc.