I am trying to implement a vector. I found this code where the writer deallocates a vector:
impl<T> Drop for MyVec<T> {
fn drop(&mut self) {
if self.cap != 0 {
while let Some(_) = self.pop() { }
let layout = Layout::array::<T>(self.cap).unwrap();
unsafe {
alloc::dealloc(self.ptr.as_ptr() as *mut u8, layout);
}
}
}
}
Why should I drop all elements step by step at the fourth line when I know that these elements are stored contiguously and the dealloc
function will clear entire sequence in the memory?
Does this vector store pointers and these elements are written in random locations? What is the purpose of dropping elements separately?