I have an ArrayIterator
that implements Iterator
over some Object
type defined as
pub struct ArrayIterator {
start: *const Object,
end: *const Object,
}
I first tried implementing Drop
for it like so:
impl Drop for ArrayIterator {
fn drop(&mut self) {
let remaining = unsafe { self.end.offset_from(self.start) } as usize;
let _ = unsafe {
Vec::from_raw_parts(
self.start as *mut Object,
remaining,
remaining,
)
};
}
}
which seems to cause a segfault when dropping an ArrayIterator
whose start
and end
differ. Not really sure why that's the case, I thought creating a Vec
would reclaim the heap memory and when that goes out of scope the Drop
impl of Vec
is run, which frees the memory.
Changing the above to this fixes it:
impl Drop for ArrayIterator {
fn drop(&mut self) {
while self.start != self.end {
unsafe {
ptr::drop_in_place(self.start as *mut Object);
self.start = self.start.offset(1);
}
}
}
}