Reference Cycle

Reference Cycle is a phenomenon in Rust when the reference count from #202206221720 can’t go down to 0 because references are referring or pointing to each other. Since the reference count of Rc<T> is never going to be 0, it will not be clean up by Rust in runtime, in turn cause memory leak (unused memory). This is quite common when the codebase use 202206232210# with a combination of Rc<T> (in the form of RefCell<Rc<T>>).

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>).

Links to this page
  • 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>).

  • Rust RefCell

    RefCell<T> can combine with 202206221720 to allow multiple ownership on mutable reference. That being said, be aware of the possibility of having 202206251349#.

  • 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 #test