gpt4 book ai didi

rust - 为什么 BufWriter 将内部 Write 包装在一个 Option 中?

转载 作者:行者123 更新时间:2023-11-29 07:58:36 25 4
gpt4 key购买 nike

在标准库中,BufWriter声明如下:

pub struct BufWriter<W: Write> {
inner: Option<W>,
buf: Vec<u8>,
// #30888: If the inner writer panics in a call to write, we don't want to
// write the buffered data a second time in BufWriter's destructor. This
// flag tells the Drop impl if it should skip the flush.
panicked: bool,
}

正如文档告诉我们的那样,panicked 的存在是为了防止在展开时出现双重写入,我理解其背后的原因。内部编写器被包裹在 Option 中是否有类似的原因?我在代码中找到的唯一部分 Option 实际被清除的地方是 into_inner但我看不出为什么这也不能用裸值来实现,因为 self 是按值取的。

最佳答案

原因很简单:BufWriter 实现了Drop,并且您不能从实现了Drop 的类型中移出字段。就在 BufWriter::into_inner 返回之前,调用了 BufWriter::drop,因为 BufWriter 被移入了函数的 self 参数,然后超出范围——这是标准的 RAII。

如果您能够移出一个字段,那么析构函数会发生什么?要么它根本不会被调用,这会令人惊讶,要么它会在某些包含无效值的字段中被调用,这可能会违反内存安全。

关于rust - 为什么 BufWriter 将内部 Write 包装在一个 Option 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48980186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com