本文介绍了使用RefCell和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:
另请参阅:
- 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处理循环图中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!