走进 Rust:引用计数智能指针
Rust 大约 837 字概念
单个值可能会有多个所有者。
记录一个值引用的数量来知晓这个值是否仍在被使用。如果某个值有零个引用,就代表没有任何有效引用并可以被清理。
Rc
Rc<T>
只能用于单线程场景。
代码
调用Rc::clone
加引用计数,调用Rc::strong_count
获得强引用的个数。
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)))));
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));
}
输出
count after creating a = 1
count after creating b = 2
count after creating c = 3
count after c goes out of scope = 2
阅读 351 · 发布于 2023-04-12
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Nginx 配置之解决 413 错误(Request Entity Too Large)阅读 5573
-
Linux 统计文本行数阅读 1616
-
package.json 中的依赖包版本号阅读 545
-
Spring Boot 设置 Cookie 和 Session 过期时间阅读 7583
-
Linux 之 CentOS 安装 JDK 及 JRE阅读 2858
-
Rust 使用 Cargo 创建和运行工程阅读 316
-
Linux 配置 top 命令显示 swap阅读 5366
-
Java 中的强引用、软引用、弱引用、虚引用、引用队列阅读 1550
-
minikube 挂载本地磁盘到内置虚拟机中阅读 811
-
Spring Boot JPA 打印 SQL 语句及参数阅读 1998