弱引用

弱引用Weak:

  1. 弱引用通过Rc::downgrade传递Rc实例的引用,调用Rc::downgrade会得到Weak类型的
    智能指针,同时将weak_count加1(不是将strong_count加1)
  2. 区别在于weak_count无需计数为0就可被Rc实例清理,而strong_count需要为0
  3. 可以通过Rc::downgrade方法返回Option<Rc>对象
  4. 弱引用是强引用的一个观察者,只有强引用存在的时候才有弱引用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use std::rc::Rc;
use std::cell:RefCell;
use crate::List::{Cons,Nil};
use std::rc::Weak;

enum List {
//Cons(i32,RefCell<Rc<List>>),
Cons(i32,RefCell<Weak<List>>),
Nil,
}
impl List {
fn tail(&self) -> Option<&RefCell<Weak<List>>> {
match self {
Cons(_,item) => Some(item),
Nil => None,
}
}
}
fn main() {
let a = Rc::new(Cons(5,RefCell::new(Weak::new())));//注意写法是Weak里面没有
//Nil,而Rc::new里面需要有

//a.strong_count=1,weak_count=0
println!("1,a strong count = {},weak count = {}",Rc::strong_count(&a),Rc::weak_count(&a));
println!("1 a.tail = {:?}",a.tail());

//b指向a
//a.strong_count=1,a.weak_count=1,因为b对a进行了引用
//b.strong_count=1,b.weak_count=0,
let b = Rc::new(Cons(10,RefCell::new(Weak::new())));
if let Some(link) = b.tail() {
*link.borrow_mut() = Rc::downgrade(&a);
}
println!("2,a strong count = {},weak count = {}",Rc::strong_count(&a),Rc::weak_count(&a));
println!("2,b strong count = {},weak count = {}",Rc::strong_count(&b),Rc::weak_count(&b));
println!("2 b.tail = {:?}",b.tail());


//a指向b
//a.strong_count=1,a.weak_count=1,因为b对a进行了引用
//b.strong_count=1,b.weak_count=1,
if let Some(link) = a.tail() {
*link.borrow_mut = Rc::downgrade(&b);
}
println!("3,a strong count = {},weak count = {}",Rc::strong_count(&a),Rc::weak_count(&a));
println!("3,b strong count = {},weak count = {}",Rc::strong_count(&b),Rc::weak_count(&b));
//此时a.tail=Some(RefCell {value: {Weak}})
println!("3 b.tail = {:?}",a.tail());


}