Rust Weak Pointer

Weak<T> is a kind of #202111301656 that doesn’t possess ownership of a variable or an object and avoid 202206251349# that could be created from #202206232210 (especially RefCell<Rc<T>>) by replacing #202206221720. It can be obtained from Rc<T> with the method Rc::downgrade. All Weak<T> will be clean up once they are out of scope, regardless of the value of weak_count (from Rc<T>).

To test the validity of Weak<T>, that is, whether it is pointing to a still alive variable, is to inspect the return value of the method Weak::upgrade (it returns Option<Rc<T>>) using match.

Links to this page
  • Rust Smart Pointers
    202206251329# which doesn’t possess variable’s ownership.
  • Reference Cycle

    Suggested solutions from the official Rust book is to detect it with automated #test, code review or data structure reorganisation to either express ownership (avoid RefCell<T> at all cost) or not at all (use 202206251329# instead of Rc<T>).

  • Reference Counting Pointer

    If there is a case where ownership should be not owned by other but sharing is still necessary (to avoid 202206251349#), use the method Rc::downgrade to get a 202206251329#. We can track how many Weak<T> are in the scope using Rc::weak_count(&{Rc<T>}). Unlike strong_count, Rc<T> will be clean up regardless of the value of weak_count since Weak<T> doesn’t possess the ownership of the reference.

#rust #memory #resource