summaryrefslogtreecommitdiff
path: root/smart_pointer
diff options
context:
space:
mode:
Diffstat (limited to 'smart_pointer')
-rw-r--r--smart_pointer/src/main.rs15
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));
}