Rc智能指针

Rc智能指针

Rc允许程序的多个部分之间只读 的共享数据,因为相同位置的多个
可变引用可能会造成数据竞争和不一致

如图所示:A、B、C三个指针都拥有A变量中值的所有权,这个时候需要使用Rc智能指针

  • 错误写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//错误写法:list没有实现copy trait,所以不能够使用b和c 同时move a的值
//enum List {
// Cons(i32,Box<List>),
// Nil,
// }
//
//use crate::List::{Cons,Nil};
//
//fn main() {
// let a = Cons(5,Box::new(Cons(10,Box::new(Nil))));
//
// let b = Cons(3,Box::new(a)); //a的所有权发生转移
//
// let c = Cons(4,BOx::new(a)); //报错点,a已经在b中使用
// }
  • 正确写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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)))));

let b = Cons(3,Rc::clone(&a));
//第二种写法
//let b = Cons(3,a.clone());

let c = Cons(4,Rc::clone(&a));
}

Rc智能指针的原理

对拥有者使用引用计数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
enum List {
Cons(i32,Rc<List>),
}

use crate::List::{Cons,Nil};
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 bind to c,a count = {}",Rc::strong_count(&a));
}//drop c
println!("count at end,a count = {}",Rc::strong_count(&a));
}