From 07a91ba7de7dfc0ca000b67905403af48a1fc02f Mon Sep 17 00:00:00 2001 From: Unisko PENG Date: Wed, 10 May 2023 15:18:22 +0800 Subject: [PATCH] Update Ch15 --- projects/drop_func_demo/Cargo.toml | 8 ++++++++ projects/drop_func_demo/src/main.rs | 19 +++++++++++++++++++ src/Ch15_Smart_Pointers.md | 8 +++++--- 3 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 projects/drop_func_demo/Cargo.toml create mode 100644 projects/drop_func_demo/src/main.rs diff --git a/projects/drop_func_demo/Cargo.toml b/projects/drop_func_demo/Cargo.toml new file mode 100644 index 0000000..0c18b1d --- /dev/null +++ b/projects/drop_func_demo/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "drop_func_demo" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/projects/drop_func_demo/src/main.rs b/projects/drop_func_demo/src/main.rs new file mode 100644 index 0000000..73cdd67 --- /dev/null +++ b/projects/drop_func_demo/src/main.rs @@ -0,0 +1,19 @@ +struct CustomSmartPointer { + data: String, +} + +impl Drop for CustomSmartPointer { + fn drop(&mut self) { + println! ("正在使用数据 `{}` 弃用 CustomSmartPointer!", self.data); + } +} + +fn main() { + let c = CustomSmartPointer { + data: String::from("我的事情"), + }; + + println! ("已创建出一个 CustomSmartPointer 实例。"); + drop(c); + println! ("在 main 结束之前这个 CustomSmartPointer 已被弃用。") +} diff --git a/src/Ch15_Smart_Pointers.md b/src/Ch15_Smart_Pointers.md index 855c042..a3d5c6c 100644 --- a/src/Ch15_Smart_Pointers.md +++ b/src/Ch15_Smart_Pointers.md @@ -610,15 +610,17 @@ $ cargo run 文本 ``正在使用数据 `一些数据` 弃用 CustomSmartPointer!`` 被打印在 `已创建出一个 CustomSmartPointer 实例。` 与 `在 main 结束之前这个 CustomSmartPointer 已被弃用。` 之间,显示 `drop` 方法在这个时间点被调用来弃用 `c`。 -咱们可以许多种方式,使用 `Drop` 特质实现中所指明的代码,来令到资源清理变成方便且安全:比如就可以使用这种技巧,来创建出咱们自己的内存分配器!有了这个 `Drop` 特质及 Rust 的所有权系统,由于 Rust 会自动完成资源的清理,因此咱们就不必一定要记得清理资源了。 +咱们可以通过多种方式使用 `Drop` 特质实现中指定的代码,来方便和安全地进行清理:例如,咱们可以用他来创建咱们自己的内存分配器! 有了 `Drop` 特质和 Rust 的所有权系统,咱们不需要记得清理内存,因为 Rust 会自动完成。 -咱们还不必担心,意外清理仍在使用中的一些值而导致的问题:确保引用始终有效的所有权系统,会确保 `drop` 只会在该值不再会被使用时才被调用。 +咱们也不必担心因意外清理仍在使用的值而导致的问题:确保引用始终有效的所有权系统,还确保在值不再被使用时,`drop` 只被调用一次。 -既然咱们已经检视了 `Box` 及灵巧指针的一些特征,接下来就要看看定义在标准库中的个别其他灵巧指针了。 +现在我们已经研究了 `Box` 和灵巧指针的一些特性,让我们看看标准库中定义的其他几个智能指针。 ## `Rc`,引用计数灵巧指针 +**`Rc`, the Reference Counted Smart Pointer** + 大多数情况下,所有权都是明确的:咱们确切知道,是哪个变量拥有者某个给定值。然而,单个值可能有着多个所有者的情形,也是有的。比如,在图数据结构(graph data structures),多条边就可能指向同一节点,从概念上讲,而那个节点就是被所有指向他的边所拥有的。在已不再有任何边指向节点,进而该节点已无所有者之前,这个节点就不应被清理掉。 必须通过使用 Rust 的类型 `Rc`,来显式地启用多重所有权,`Rc` 即 *引用计数,reference counting* 的缩写。`Rc` 类型会追踪某个值的引用数,从而判断出该值是否仍在使用中。在到某个值的引用数为零时,该值就可以在不会有任何引用变成无效的情况下,(安全地)被清理掉。