当前位置:网站首页>RC smart pointer in rust

RC smart pointer in rust

2022-04-23 18:03:00 Xu Yeping

Rust Medium Rc Intelligent pointer

1 First time to know Rc

Let's start with a simple example :

use std::rc::Rc;
fn main() {
    
    let x = Rc::new(123);
    println!("{:?}", x);
}
---------------------------------------------------
cargo run
123

This with Box The pointer is almost the same , The difference between them is clone() Specific implementation process of .

2 clone() Method

See the following example :

use std::rc::Rc;
fn main() {
    
    let x = Rc::new(123);
    let y = x.clone();
    println!("{:?}, {:?}", x, y);
}
---------------------------------------------------
cargo run
123, 123

Look and Box Do not have what difference . We can Rc Switch to Box, The result is the same . The difference between them is the internal execution process .Rc This clone(), There is no real replication of data , It's an address that shares the same data , And use an internal counter to record the number of references . Every time you execute clone() When the method is used , Add one counter , Every time you execute drop() When the method is used , Counter minus one . Once the counter is zero , Then clean up the actual data .

Personal feeling , This mechanism is better than C++ Smart pointers are easy to implement , Easier to understand , It's less error prone to use . I'll write an article about C++ Comparison of intelligent pointer implementation mechanism .

版权声明
本文为[Xu Yeping]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230544498606.html