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<T>, 引用计数智能指针

在大多数情况下,所有权是明确的:你确切地知道哪个变量拥有给定的值。然而,存在单个值可能有多个所有者的情况。例如,在图数据结构中,多个边可能指向同一个节点,该节点在概念上由所有指向它的边共同拥有。除非节点没有任何边指向它,因此没有任何所有者,否则不应清理该节点。

您必须通过使用 Rust 类型 Rc<T> 显式启用多重所有权,这是 引用计数 的缩写。Rc<T> 类型跟踪对一个值的引用数量,以确定该值是否仍在使用中。如果对一个值的引用数量为零,该值可以被清理,而不会使任何引用失效。

想象 Rc<T> 像是家庭房间里的电视。当一个人进入房间看电视时, 他们会打开电视。其他人可以进入房间一起看电视。当最后一个人离开房间时, 他们会关掉电视,因为电视不再被使用。 如果有人在其他人还在看电视时关掉电视,剩下的电视观众会非常不满!

当我们希望在堆上分配一些数据,供程序的多个部分读取,并且无法在编译时确定哪一部分会最后使用完这些数据时,我们会使用Rc<T>类型。如果我们知道哪一部分会最后使用完,就可以让那一部分成为数据的所有者,那么编译时强制执行的正常所有权规则就会生效。

请注意,Rc<T> 仅用于单线程场景。当我们在第 16 章讨论并发时,我们将介绍如何在多线程程序中进行引用计数。

使用 Rc<T> 共享数据

让我们回到第 15-5 列表中的 cons 列表示例。回想一下,我们使用 Box<T> 定义了它。这次,我们将创建两个列表,它们都共享第三个列表的所有权。从概念上讲,这看起来类似于图 15-3。

A linked list with the label 'a' pointing to three elements: the first element contains the integer 5 and points to the second element. The second element contains the integer 10 and points to the third element. The third element contains the value 'Nil' that signifies the end of the list; it does not point anywhere. A linked list with the label 'b' points to an element that contains the integer 3 and points to the first element of list 'a'. A linked list with the label 'c' points to an element that contains the integer 4 and also points to the first element of list 'a', so that the tail of lists 'b' and 'c' are both list 'a'

图15-3: 两个列表,bc,共享第三个列表 a 的所有权

我们将创建一个包含 5 和 10 的列表 a。然后我们将创建两个更多的列表:b 以 3 开头,c 以 4 开头。bc 两个列表都将接着包含 5 和 10 的第一个 a 列表。换句话说,两个列表都将共享包含 5 和 10 的第一个列表。

尝试使用我们的 List 定义和 Box<T> 实现这个场景是行不通的,如清单 15-17 所示。

Filename: src/main.rs
enum List {
    Cons(i32, Box<List>),
    Nil,
}

use crate::List::{Cons, Nil};

fn main() {
    let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));
    let b = Cons(3, Box::new(a));
    let c = Cons(4, Box::new(a));
}
Listing 15-17: Demonstrating that we’re not allowed to have two lists using Box<T> that try to share ownership of a third list

当我们编译这段代码时,我们得到这个错误:

$ cargo run
   Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0382]: use of moved value: `a`
  --> src/main.rs:11:30
   |
9  |     let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));
   |         - move occurs because `a` has type `List`, which does not implement the `Copy` trait
10 |     let b = Cons(3, Box::new(a));
   |                              - value moved here
11 |     let c = Cons(4, Box::new(a));
   |                              ^ value used here after move

For more information about this error, try `rustc --explain E0382`.
error: could not compile `cons-list` (bin "cons-list") due to 1 previous error

Cons 变体拥有它们持有的数据,因此当我们创建 b 列表时,a 被移动到 b 中,b 拥有 a。然后,当我们尝试在创建 c 时再次使用 a,我们不被允许这样做,因为 a 已经被移动。

我们可以将 Cons 的定义更改为持有引用,但这样我们就必须指定生命周期参数。通过指定生命周期参数,我们将指定列表中的每个元素至少与整个列表一样长。这是列表 15-17 中元素和列表的情况,但并非所有情况都是如此。

相反,我们将更改 List 的定义,用 Rc<T> 替换 Box<T>,如清单 15-18 所示。每个 Cons 变体现在将持有一个值和一个指向 ListRc<T>。当我们创建 b 时,不是获取 a 的所有权,而是克隆 a 持有的 Rc<List>,从而将引用数从一增加到二,使 ab 共享该 Rc<List> 中的数据的所有权。在创建 c 时,我们也会克隆 a,将引用数从二增加到三。每次调用 Rc::clone 时,Rc<List> 中数据的引用计数都会增加,除非引用计数为零,否则数据不会被清理。

Filename: src/main.rs
enum List {
    Cons(i32, Rc<List>),
    Nil,
}

use crate::List::{Cons, Nil};
use std::rc::Rc;

fn main() {
    let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    let b = Cons(3, Rc::clone(&a));
    let c = Cons(4, Rc::clone(&a));
}
Listing 15-18: A definition of List that uses Rc<T>

我们需要添加一个 use 语句来将 Rc<T> 引入作用域,因为它不在前言中。在 main 中,我们创建了一个包含 510 的列表,并将其存储在 a 中的新 Rc<List> 中。然后,当我们创建 bc 时,我们调用 Rc::clone 函数并将 a 中的 Rc<List> 的引用作为参数传递。

我们可以调用 a.clone() 而不是 Rc::clone(&a),但 Rust 的惯例是在这种情况下使用 Rc::cloneRc::clone 的实现不会像大多数类型的 clone 实现那样对所有数据进行深度复制。调用 Rc::clone 只是增加引用计数,这不会花费太多时间。数据的深度复制可能会花费很多时间。通过使用 Rc::clone 进行引用计数,我们可以从视觉上区分深度复制类型的克隆和增加引用计数类型的克隆。在查找代码中的性能问题时,我们只需要考虑深度复制的克隆,可以忽略对 Rc::clone 的调用。

克隆 Rc<T> 会增加引用计数

让我们修改列表 15-18 中的工作示例,以便在我们创建和删除对 a 中的 Rc<List> 的引用时,可以看到引用计数的变化。

在清单 15-19 中,我们将更改 main,使其在列表 c 周围有一个内部作用域;然后我们可以看到当 c 超出作用域时引用计数如何变化。

Filename: src/main.rs
enum List {
    Cons(i32, Rc<List>),
    Nil,
}

use crate::List::{Cons, Nil};
use std::rc::Rc;

// --snip--

fn main() {
    let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    println!("count after creating a = {}", Rc::strong_count(&a));
    let b = Cons(3, Rc::clone(&a));
    println!("count after creating b = {}", Rc::strong_count(&a));
    {
        let c = Cons(4, Rc::clone(&a));
        println!("count after creating c = {}", Rc::strong_count(&a));
    }
    println!("count after c goes out of scope = {}", Rc::strong_count(&a));
}
Listing 15-19: Printing the reference count

在程序中每次引用计数发生变化时,我们都会打印引用计数,这是通过调用 Rc::strong_count 函数获得的。这个函数被称为 strong_count 而不是 count,因为 Rc<T> 类型还有 weak_count;我们将在 “使用 Weak<T> 防止引用循环” 中看到 weak_count 的用途。

这段代码打印以下内容:

$ cargo run
   Compiling cons-list v0.1.0 (file:///projects/cons-list)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.45s
     Running `target/debug/cons-list`
count after creating a = 1
count after creating b = 2
count after creating c = 3
count after c goes out of scope = 2

我们可以看到,a 中的 Rc<List> 初始引用计数为 1;然后 每次我们调用 clone,计数增加 1。当 c 超出作用域时, 计数减少 1。我们不需要像调用 Rc::clone 增加引用计数那样调用一个函数来减少 引用计数:Drop 特性的实现会在 Rc<T> 值超出作用域时自动减少引用计数。

在这个例子中我们看不到的是,当 b 和然后 amain 结束时超出作用域,计数变为 0,Rc<List> 完全被清理。使用 Rc<T> 允许单个值有多个所有者,计数确保只要任何一个所有者仍然存在,值就保持有效。

通过不可变引用,Rc<T> 允许你在程序的多个部分之间共享数据,但仅限于读取。如果 Rc<T> 也允许你有多个可变引用,你可能会违反在第 4 章讨论的借用规则之一:对同一位置的多个可变借用可能导致数据竞争和不一致。但能够修改数据是非常有用的!在下一节中,我们将讨论内部可变性模式和 RefCell<T> 类型,你可以将其与 Rc<T> 结合使用,以应对这种不可变性限制。