]> git.proxmox.com Git - rustc.git/blame - src/doc/nomicon/src/vec-dealloc.md
New upstream version 1.54.0+dfsg1
[rustc.git] / src / doc / nomicon / src / vec-dealloc.md
CommitLineData
8bb4bdeb 1# Deallocating
c1a9b12d
SL
2
3Next we should implement Drop so that we don't massively leak tons of resources.
4The easiest way is to just call `pop` until it yields None, and then deallocate
5our buffer. Note that calling `pop` is unneeded if `T: !Drop`. In theory we can
6ask Rust if `T` `needs_drop` and omit the calls to `pop`. However in practice
7LLVM is *really* good at removing simple side-effect free code like this, so I
8wouldn't bother unless you notice it's not being stripped (in this case it is).
9
17df50a5 10We must not call `alloc::dealloc` when `self.cap == 0`, as in this case we
c1a9b12d
SL
11haven't actually allocated any memory.
12
c1a9b12d
SL
13```rust,ignore
14impl<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```