使用RefCell和Rc处理循环图中的内存泄漏

时间:2017-12-14 21:46:21

标签: memory-management graph memory-leaks rust

我按照https://ricardomartins.cc/2016/06/08/interior-mutability中提到的方法,使用RcRefCell在Rust中创建图表。

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 }
    }

}

我认为这种方法会在循环图的情况下导致内存泄漏。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您不必阅读博客文章才能找到答案,只需read the documentation

  

Rc指针之间的循环永远不会被释放。因此,Weak用于打破周期。例如,一棵树可以有从父节点到子节点的强Rc指针,以及从子节点到父节点的Weak指针。

另见: