mirror of https://github.com/rust-lang/nomicon
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
30 lines
1.0 KiB
30 lines
1.0 KiB
8 years ago
|
# Deallocating
|
||
10 years ago
|
|
||
|
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 deallocate
|
||
9 years ago
|
our buffer. Note that calling `pop` is unneeded if `T: !Drop`. In theory we can
|
||
|
ask Rust if `T` `needs_drop` and omit the calls to `pop`. However in practice
|
||
|
LLVM is *really* good at removing simple side-effect free code like this, so I
|
||
|
wouldn't bother unless you notice it's not being stripped (in this case it is).
|
||
10 years ago
|
|
||
9 years ago
|
We must not call `heap::deallocate` when `self.cap == 0`, as in this case we
|
||
|
haven't actually allocated any memory.
|
||
10 years ago
|
|
||
|
|
||
10 years ago
|
```rust,ignore
|
||
10 years ago
|
impl<T> Drop for Vec<T> {
|
||
|
fn drop(&mut self) {
|
||
|
if self.cap != 0 {
|
||
|
while let Some(_) = self.pop() { }
|
||
|
|
||
10 years ago
|
let align = mem::align_of::<T>();
|
||
10 years ago
|
let elem_size = mem::size_of::<T>();
|
||
|
let num_bytes = elem_size * self.cap;
|
||
|
unsafe {
|
||
9 years ago
|
heap::deallocate(*self.ptr as *mut _, num_bytes, align);
|
||
10 years ago
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
```
|