使用RefCell和Rc处理循环图中的内存泄漏 [英] Handling memory leak in cyclic graphs using RefCell and Rc

查看:169
本文介绍了使用RefCell和Rc处理循环图中的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了 https://ricardomartins.cc/2016/06中提到的方法/08/interior-mutability 用于使用RcRefCell在Rust中创建图形.

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?

推荐答案

您无需阅读博客即可找到答案,只需

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

Rc指针之间的循环永远不会被释放.因此,Weak用于中断循环.例如,一棵树可以具有从父节点到子节点的强Rc指针,以及从子节点到其父节点的Weak指针.

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.

另请参阅:

  • 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

这篇关于使用RefCell和Rc处理循环图中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆