【问题标题】:How does Vec::push work for self referencing types?Vec::push 如何为自引用类型工作?
【发布时间】:2023-01-12 11:14:36
【问题描述】:

引自vec::push 实现:

pub fn push(&mut self, value: T) {
    // This will panic or abort if we would allocate > isize::MAX bytes
    // or if the length increment would overflow for zero-sized types.
    if self.len == self.buf.capacity() {
        self.buf.reserve_for_push(self.len);
    }
    unsafe {
        let end = self.as_mut_ptr().add(self.len);
        ptr::write(end, value);
        self.len += 1;
    }
}

这里如果T是自引用类型,如何保证在ptr::write之后在end有一个有效的对象?

【问题讨论】:

  • T 怎么能自我引用呢?据我所知,只有Pinned 对象可以有自引用,但固定对象总是在指针后面,不能移动。如果 U 类型是自引用的,那么您只能通过 Pin<U> 指针(不是自引用)进行访问。

标签: rust self-reference


【解决方案1】:

在 Rust 中,所有类型都是可移动的,因此在移动后必须有效; ptr::write 本质上只是将值移动到新位置。

自引用对象只能隐藏在Pin 后面以避免被移动,这不是因为编译器专门处理它们而是Pin 只是避免提供对“不可移动”值的&mut T 的访问。但是图钉本身仍然可以移动,因此将一个图钉传递给.push() 不是问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2011-07-03
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多