BronzeRust 垃圾回收器

联合创作 · 2023-10-01 19:56

Bronze 是用于 Rust 的基于库的垃圾回收器。


Bronze 通过引入一种新的智能指针类型 GcRef 来放宽 Rust 的部分限制,GcRef 描述了一个指向垃圾回收堆位置 (heap location) 的指针。使用 Bronze 时,位于堆栈 (stack) 上的数据具有所有常见的 Rust ownership 要求。但 Bronze 允许将数据移动到堆 (heap)。如果类型的值T在堆上,Bronze 允许GcRef<T>对该值进行任意数量的类型引用。


示例


如果不使用 Bronze,则需要仔细管理引用和生命周期:



pub struct IntContainer {
n: i32,
}

pub fn set(c: &mut IntContainer, n: i32) {
c.n = n;
}

pub fn test() {
let c1 = IntContainer{n: 42};
let mut c2 = c1;

// Can't use c1 anymore because it's been moved to c2
set(&mut c2, 42);
}

使用 Bronze



//
#[derive(Trace, Finalize)]
pub struct IntContainer {
n: i32,
}

pub fn set(mut c: GcRef<IntContainer>, n: i32) {
c.n = n;
}

pub fn test() {
let c1 = GcRef::new(IntContainer{n: 42});
let c2 = c1;
// Now c1 and c2 both reference the same object.

set(c2, 42);
set(c1, 43);
// Now they both reference an object with value 43.
}
浏览 20
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报