2

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user19291301
  • 127
  • 8
  • A potentially more efficient (but less safe) way to do it would be to call `std::mem::drop_in_place()` in a loop. In both cases you can wrap the loop in `if std::mem::needs_drop::() { ... }` to ensure it doesn't run if `T` doesn't implement `Drop` (or requires dropping its members, etc). – user4815162342 Mar 12 '23 at 21:18
  • @user4815162342 The more efficient, and also correct, and also not requiring `needs_drop()`, is to construct a pointer to slice containing all elements and call `drop_in_place()` on it. – Chayim Friedman Mar 13 '23 at 06:39
  • @ChayimFriedman Are you sure? Calling `drop_in_place` on a slice doesn't seem useful, as the slice doesn't own the underlying data. – user4815162342 Mar 13 '23 at 07:10
  • @user4815162342 I'm very sure. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=17d473252d2318d8ea1af452695fa03a – Chayim Friedman Mar 13 '23 at 07:13
  • @ChayimFriedman Very nice, thanks for the example! – user4815162342 Mar 13 '23 at 07:21

1 Answers1

6

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.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157