Deallocating

Next we should implement Drop so that we don’t massively leak tons of resources.The easiest way is to just call pop until it yields None, and then deallocateour buffer. Note that calling pop is unneeded if T: !Drop. In theory we canask Rust if T needs_drop and omit the calls to pop. However in practiceLLVM is really good at removing simple side-effect free code like this, so Iwouldn’t bother unless you notice it’s not being stripped (in this case it is).

We must not call heap::deallocate when self.cap == 0, as in this case wehaven’t actually allocated any memory.

  1. impl<T> Drop for Vec<T> {
  2. fn drop(&mut self) {
  3. if self.cap != 0 {
  4. while let Some(_) = self.pop() { }
  5. let align = mem::align_of::<T>();
  6. let elem_size = mem::size_of::<T>();
  7. let num_bytes = elem_size * self.cap;
  8. unsafe {
  9. heap::deallocate(self.ptr.as_ptr() as *mut _, num_bytes, align);
  10. }
  11. }
  12. }
  13. }