BronzeRust 垃圾回收器
Bronze 是用于 Rust 的基于庫的垃圾回收器。
Bronze 通過引入一種新的智能指針類型 GcRef 來放寬 Rust 的部分限制,GcRef 描述了一個(gè)指向垃圾回收堆位置 (heap location) 的指針。使用 Bronze 時(shí),位于堆棧 (stack) 上的數(shù)據(jù)具有所有常見的 Rust ownership 要求。但 Bronze 允許將數(shù)據(jù)移動(dòng)到堆 (heap)。如果類型的值T在堆上,Bronze 允許GcRef<T>對(duì)該值進(jìn)行任意數(shù)量的類型引用。
示例
如果不使用 Bronze,則需要仔細(xì)管理引用和生命周期:
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.
}評(píng)論
圖片
表情
