struct Device;
struct CommandBuffer {
device: &Device,
// ...
}
// Does not work because Rust does not allow internal pointers
struct Something {
device: Device,
command_buffer: CommandBuffer,
}
一个解决方案是使用 Arc
struct CommandBuffer {
device: Arc<Device>,
// ...
}
struct Something {
device: Arc<Device>,
command_buffer: CommandBuffer,
}
Arc
的缺点是间接性、原子计数器以及逃脱作用域并保持 Device
事件的可能性。
现在我不认为你可以绕过 Rust 中的一个间接级别,但是否有可能在 Box
和 Arc
之间创建一些东西?
struct CommandBuffer {
device: BoxRef<Device>,
// ...
}
struct Something {
device: Box<Device>,
command_buffer: CommandBuffer,
}
我在尝试实现 BoxRef
时遇到的主要问题是我需要能够移动 Box
,即使当前有借用它也是如此。由于间接级别,这在技术上应该是安全的,但我认为目前不能用 Rust 表达。
let boxed_device = Box::new(device);
let device_ref = boxed_device.boxed_ref();
// Owner of the reference should be allowed to move
Something{device: boxed_device, CommandBuffer{device: device_ref}}
BoxRef
可以实现吗?我快速浏览了一下 owning_ref 但它似乎并没有解决我的问题。我还有哪些其他选项可以在 Rust 中表达“内部指针”?
最佳答案
这会起作用:
struct Device;
struct CommandBuffer<'a> {
device: &'a Device, // ...
}
struct Something<'a> {
device: &'a Device,
command_buffer: CommandBuffer<'a>,
}
fn main() {
let dev = Device;
let smth = Something {
device: &dev,
command_buffer: CommandBuffer { device: &dev },
};
}
你不应该担心 Arc
性能那么。
通过编写一个保持 Arc
的新类型可以很容易地处理逃逸范围的可能性。私有(private)的,只实现 Deref
至 &T
没有Clone
.
关于rust - 是否可以在不使用 `internal pointers` 的情况下拥有 `Arc` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39079922/