From 5858e3d5c7033f09b7fb2c006a2e227d0cff3d89 Mon Sep 17 00:00:00 2001 From: Jordan Gong Date: Sun, 20 Sep 2020 18:48:59 +0800 Subject: Count references `Rc` --- smart_pointer/src/main.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) (limited to 'smart_pointer/src/main.rs') 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), + Cons(i32, Rc), 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)); } -- cgit v1.2.3