Created
August 24, 2021 11:44
-
-
Save mitghi/671979443740ed8607a8f5d6299164aa to your computer and use it in GitHub Desktop.
reference count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::rc::Rc; | |
use std::cell::RefCell; | |
struct A { | |
value: Rc<RefCell<Vec<i64>>>, | |
} | |
struct B { | |
value: Rc<RefCell<Vec<i64>>>, | |
} | |
impl A { | |
fn new(mut v: Vec<i64>) -> A { | |
A { | |
value: Rc::new(RefCell::new(v)) | |
} | |
} | |
} | |
impl B { | |
fn new(mut v: Rc<RefCell<Vec<i64>>>) -> B { | |
B { value: v } | |
} | |
} | |
impl Drop for A { | |
fn drop(&mut self) { | |
println!("dropping A"); | |
} | |
} | |
impl Drop for B { | |
fn drop(&mut self) { | |
println!("dropping B"); | |
} | |
} | |
fn main() { | |
let a = A::new(Vec::new()); | |
a.value.borrow_mut().push(20); | |
let mut b = Some(a.value.clone()); | |
b.unwrap().borrow_mut().push(30); | |
println!("Hello, world!"); | |
{ | |
let b2 = B::new(a.value.clone()); | |
b2.value.borrow_mut().push(40); | |
b2.value.borrow_mut().push(200); | |
} | |
b = None; | |
let c3 = a.value.clone(); | |
c3.borrow_mut().push(100); | |
println!("reference count: {}", Rc::strong_count(&a.value)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment