diff options
author | Jordan Gong <jordan.gong@protonmail.com> | 2020-09-20 18:48:59 +0800 |
---|---|---|
committer | Jordan Gong <jordan.gong@protonmail.com> | 2020-09-20 18:48:59 +0800 |
commit | 5858e3d5c7033f09b7fb2c006a2e227d0cff3d89 (patch) | |
tree | 25de487ac695a54f3ee9fc7f84b04e96cf4a7c3e /smart_pointer/src/main.rs | |
parent | 0c6091d677c970f57bd18b3edc09b440014f8621 (diff) |
Count references `Rc`
Diffstat (limited to 'smart_pointer/src/main.rs')
-rw-r--r-- | smart_pointer/src/main.rs | 15 |
1 files changed, 13 insertions, 2 deletions
diff --git a/smart_pointer/src/main.rs b/smart_pointer/src/main.rs index d0be410..6778671 100644 --- a/smart_pointer/src/main.rs +++ b/smart_pointer/src/main.rs @@ -1,6 +1,7 @@ // Recursive type using boxes +use std::rc::Rc; enum List { - Cons(i32, Box<List>), + Cons(i32, Rc<List>), Nil, } @@ -38,7 +39,7 @@ fn main() { println!("b = {}", b); use crate::List::{Cons, Nil}; - let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); + let list = Cons(1, Rc::new(Cons(2, Rc::new(Cons(3, Rc::new(Nil)))))); // Dereferencing let x = 5; @@ -79,4 +80,14 @@ fn main() { println!("CustomSmartPointer created."); drop(c); println!("CustomSmartPointer dropped before the end of 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 creating c = {}", Rc::strong_count(&a)); + } + println!("count after c goes out of scope = {}", Rc::strong_count(&a)); } |