rustvectormemory-managementdrop

Why elements should be dropped before dropping vec in rust


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?


Solution

  • Think about a MyVec<String>. Every string in the vector has its own separate allocation to hold the string data.

    The vector can only free the memory it allocated itself, which holds the string objects, but not the data the strings in turn hold. So it must ask each string individually to free up its extra resources, and that's exactly what drop does.