我查看了Drain Filter的Drop实现,以确保它删除所有剩余的元素,并且我注意到它在每drop(item);
个元素周围都有一个DropGuard for Self(这是Drain Filter迭代器).这个卫兵有什么用处?除非drop(item);
人感到panic ,否则我看不出这么做的目的.这仅仅是为了确保即使发生panic 也能移除其余物品吗?为什么不使用CATCH_UNWIND呢?
相关删除实施:
impl<T, F> Drop for DrainFilter<'_, T, F>
where
F: FnMut(&mut T) -> bool,
{
fn drop(&mut self) {
struct DropGuard<'r, 'a, T, F>(&'r mut DrainFilter<'a, T, F>)
where
F: FnMut(&mut T) -> bool;
impl<'r, 'a, T, F> Drop for DropGuard<'r, 'a, T, F>
where
F: FnMut(&mut T) -> bool,
{
fn drop(&mut self) {
self.0.for_each(drop);
}
}
while let Some(item) = self.next() {
let guard = DropGuard(self);
drop(item);
mem::forget(guard);
}
}
}