使用RefCell和Rc处理循环图中的内存泄漏 [英] Handling memory leak in cyclic graphs using RefCell and Rc
问题描述
我遵循了 https://ricardomartins.cc/2016/06中提到的方法/08/interior-mutability 用于使用Rc
和RefCell
在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 strongRc
pointers from parent nodes to children, andWeak
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屋!