]>
Commit | Line | Data |
---|---|---|
8bb4bdeb | 1 | # Deallocating |
c1a9b12d SL |
2 | |
3 | Next we should implement Drop so that we don't massively leak tons of resources. | |
4 | The easiest way is to just call `pop` until it yields None, and then deallocate | |
5 | our buffer. Note that calling `pop` is unneeded if `T: !Drop`. In theory we can | |
6 | ask Rust if `T` `needs_drop` and omit the calls to `pop`. However in practice | |
7 | LLVM is *really* good at removing simple side-effect free code like this, so I | |
8 | wouldn't bother unless you notice it's not being stripped (in this case it is). | |
9 | ||
17df50a5 | 10 | We must not call `alloc::dealloc` when `self.cap == 0`, as in this case we |
c1a9b12d SL |
11 | haven't actually allocated any memory. |
12 | ||
c1a9b12d SL |
13 | ```rust,ignore |
14 | impl<T> Drop for Vec<T> { | |
15 | fn drop(&mut self) { | |
16 | if self.cap != 0 { | |
17 | while let Some(_) = self.pop() { } | |
17df50a5 | 18 | let layout = Layout::array::<T>(self.cap).unwrap(); |
c1a9b12d | 19 | unsafe { |
17df50a5 | 20 | alloc::dealloc(self.ptr.as_ptr() as *mut u8, layout); |
c1a9b12d SL |
21 | } |
22 | } | |
23 | } | |
24 | } | |
25 | ``` |