[][src]Function tao_of_rust::ch05::smart_pointer::share_ownership

pub fn share_ownership()

智能指针和所有权: Rc / Arc

Base usage: 共享所有权

use std::rc::Rc;
fn main() {
    let x = Rc::new(45);
    let y1 = x.clone(); // 增加强引用计数
    let y2 = x.clone();  // 增加强引用计数
    println!("{:?}", Rc::strong_count(&x));
    let w =  Rc::downgrade(&x);  // 增加弱引用计数
    println!("{:?}", Rc::weak_count(&x));
    let y3 = &*x;         // 不增加计数
    println!("{}", 100 - *x);
}Run

Base usage: 使用弱引用解决循环引用内存泄漏问题

use std::rc::Rc; use std::rc::Weak; use std::cell::RefCell; struct Node { next: Option<Rc<RefCell>>, head: Option<Weak<RefCell>> } impl Drop for Node { fn drop(&mut self) { println!("Dropping!"); } } fn main() { let first = Rc::new(RefCell::new(Node { next: None, head: None })); let second = Rc::new(RefCell::new(Node { next: None, head: None })); let third = Rc::new(RefCell::new(Node { next: None, head: None })); first.borrow_mut().next = Some(second.clone()); second.borrow_mut().next = Some(third.clone()); third.borrow_mut().head = Some(Rc::downgrade(&first)); }