Handling memory leak in cyclic graphs using RefCel

2019-08-21 02:33发布

问题:

I followed the approach mentioned in https://ricardomartins.cc/2016/06/08/interior-mutability for creating a graph in Rust using Rc and RefCell.

type NodeRef<i32> = Rc<RefCell<_Node<i32>>>;

#[derive(Clone)]
// The private representation of a node.
struct _Node<i32> {
    inner_value: i32,
    adjacent: Vec<NodeRef<i32>>,
}
#[derive(Clone)]
// The public representation of a node, with some syntactic sugar.
struct Node<i32>(NodeRef<i32>);

impl<i32> Node<i32> {
    // Creates a new node with no edges.
    fn new(inner: i32) -> Node<i32> {
        let node = _Node { inner_value: inner, adjacent: vec![] };
        Node(Rc::new(RefCell::new(node)))
    }

    // Adds a directed edge from this node to other node.
    fn add_adjacent(&self, other: &Node<i32>) {
        (self.0.borrow_mut()).adjacent.push(other.0.clone());
    }
}
#[derive(Clone)]
struct Graph<i32> {
    nodes: Vec<Node<i32>>,
}

impl<i32> Graph<i32> {
    fn with_nodes(nodes: Vec<Node<i32>>) -> Self {
        Graph { nodes: nodes }
    }

}

I think this approach will lead to memory leaks in case of cyclic graphs. How can I fix that?

回答1:

You don't have to read a blog post to find the answer, just read the documentation:

A cycle between Rc pointers will never be deallocated. For this reason, Weak is used to break cycles. For example, a tree could have strong Rc pointers from parent nodes to children, and Weak pointers from children back to their parents.

See also:

  • Is there a way to build a structure with cyclic links without runtime overhead?
  • Implement graph-like datastructure in Rust
  • Recursive Data Structures in Rust