Skip to content

Instantly share code, notes, and snippets.

@mitghi
Created August 24, 2021 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitghi/671979443740ed8607a8f5d6299164aa to your computer and use it in GitHub Desktop.
Save mitghi/671979443740ed8607a8f5d6299164aa to your computer and use it in GitHub Desktop.
reference count
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