1 个稳定版本
1.0.0 | 2023 年 6 月 22 日 |
---|
#660 在 内存管理
用于 cxc
7KB
121 行
Passable 🛳
传递指针。有点像 Rc
,但一次只能有一个访问者,这使得修改成为可能。当持有引用的 Pass
被丢弃时,它将引用交还给其前驱。
use passable::Pass;
let mut one = Pass::new("hello");
{
let mut two = one.pass().unwrap();
// now two has the reference, and not one.
assert_eq!(two.deref(), Some(&"hello"));
assert_eq!(one.deref(), None);
*two.deref_mut().unwrap() = "goodbye";
}
// two is dropped here, giving the reference back to one.
assert_eq!(one.deref(), Some(&"goodbye"));
你还可以在链的中间丢弃一个引用。
use passable::Pass;
let mut one = Pass::new(true);
let mut two = one.pass().unwrap();
*two.deref_mut().unwrap() = false;
let mut three = two.pass().unwrap();
std::mem::drop(two);
assert_eq!(three.deref(), Some(&false));
*three.deref_mut().unwrap() = true;
std::mem::drop(three);
assert_eq!(one.deref(), Some(&true));
注意事项
Pass
实现Default
,但它没有实现其他依赖于对内部值引用的 std 库特性,如Clone
、Debug
和Display
。如果您有关于如何在Pass
不具有内部值引用时实现这些特性的建议,请提交一个 issue!Pass
实现为链表,每个节点持有对内部值的Option<NonNull<T>>
。堆栈中的每个Pass
对象的大小为 8 字节,链表中的每个节点的大小为 24 字节。