当前位置:网站首页>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
边栏推荐
- PHP processing JSON_ Decode() parses JSON stringify
- Pytorch notes - get familiar with the network construction method by building RESNET (complete code)
- Explain of MySQL optimization
- [leetcode 59] spiral matrix II
- [leetcode 6] zigzag transformation
- Addition, deletion, modification and query of MySQL table
- ThreadLocal. Threadlocalmap analysis
- Definition of C class and method
- [leetcode 350] intersection of two arrays II
- 12. Monkeys climb mountains
猜你喜欢

基于pygame库编写的五子棋游戏
![Comparative study paper - [Moco, cvpr2020] momentum contract for unsupervised visual representation learning](/img/21/4bc94fe29f416c936436c04fc16fa8.png)
Comparative study paper - [Moco, cvpr2020] momentum contract for unsupervised visual representation learning

从源代码到可执行文件的过程

Framework analysis 1 Introduction to system architecture

Linear algebra Chapter 2 - matrices and their operations

St table template

Definition of C class and method

MySQL advanced query
![Reading of denoising papers - [cvpr2022] blind2blind: self supervised image denoising with visible blind spots](/img/fd/84df62c88fe90a73294886642036a0.png)
Reading of denoising papers - [cvpr2022] blind2blind: self supervised image denoising with visible blind spots

Addition, deletion, query and modification of data
随机推荐
Best practices for MySQL storage time
C3p0 database connection pool usage
How SYSTEMd uses / etc / init D script
Formation à la programmation
线程和进程的关系和区别是什么
IO multiplexing of 09 redis
Integration and induction of knowledge points of automatic control principle (Han min version)
Comparative study paper - [Moco, cvpr2020] momentum contract for unsupervised visual representation learning
4. Print form
RPC must know and know
Automatic control (Han min version)
Preparedstatement prevents SQL injection
In depth understanding of the relationship between dncblevel and noise denoising in the paper
How to grow at work
Understanding and installing MySQL
Techniques et principes de détection
MySQL occasional Caton
GDAL+OGR学习
自動控制(韓敏版)
Use of multithreaded executors