当前位置:网站首页>Rust 中的 Rc智能指针
Rust 中的 Rc智能指针
2022-04-23 05:45:00 【许野平】
Rust 中的 Rc智能指针
1 初识 Rc
先看个简单例子:
use std::rc::Rc;
fn main() {
let x = Rc::new(123);
println!("{:?}", x);
}
---------------------------------------------------
cargo run
123
这个与 Box 指针几乎一样,二者区别在于 clone()
的具体执行过程。
2 clone() 方法
看下面的例子:
use std::rc::Rc;
fn main() {
let x = Rc::new(123);
let y = x.clone();
println!("{:?}, {:?}", x, y);
}
---------------------------------------------------
cargo run
123, 123
看上去与 Box 没啥区别。我们可以把 Rc 换成 Box,结果是一样的。它们的区别在于内部执行过程。Rc 的这个 clone(),并没有真的复制数据,而是共享了同一份数据的地址,并利用一个内部计数器记录引用次数。每次执行 clone() 方法时,计数器加一,每次执行drop() 方法时,计数器减一。一旦计数器为零,则清理实际数据。
个人感觉,这套机制比 C++ 的智能指针实现起来容易,理解起来更容易,用起来更不容易出错。回头我会写一篇与 C++ 智能指针实现机制比较的文章。
版权声明
本文为[许野平]所创,转载请带上原文链接,感谢
https://yeping.blog.csdn.net/article/details/123042848
边栏推荐
猜你喜欢
SQL -- data definition
IO multiplexing of 09 redis
The bottom implementation principle of thread - static agent mode
scikit-learn sklearn 0.18 官方文档中文版
从源代码到可执行文件的过程
Create binary tree
檢測技術與原理
SQL injection
How to use comparative learning to do unsupervised - [cvpr22] training & [eccv20] image translation
GDAL+OGR学习
随机推荐
Delete and truncate
A general U-shaped transformer for image restoration
Basic knowledge of network in cloud computing
Implementation of displaying database pictures to browser tables based on thymeleaf
电机与拖动(戚金清版)学习整理
Explain of MySQL optimization
Stability building best practices
Consistent hash algorithm used for redis cache load balancing
MySQL best practices for creating tables
Framework analysis 2 Source code - login authentication
Why does the subscript of the array start from 0 instead of 1?
Doomsday (simple computational geometry)
卡尔曼滤波与惯性组合导航
[leetcode 383] ransom letter
C array
Create binary tree
11.a==b?
Generate excel template (drop-down selection, multi-level linkage)
程序设计训练
检测技术与原理