Skip to content

Commit d94b31e

Browse files
authored
Merge pull request #425 from pwbh/handle-drop-zst
Handle drop zst
2 parents 8b61acf + 625d9de commit d94b31e

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/vec/vec-zsts.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,3 +214,20 @@ impl<T> DoubleEndedIterator for RawValIter<T> {
214214
```
215215

216216
And that's it. Iteration works!
217+
218+
One last thing we need to consider is that when our vector is dropped, it deallocates the memory that was allocated while it was alive. With ZSTs, we didn't allocate any memory; in fact, we never do. So, right now, our code has unsoundness: we're still trying to deallocate a `NonNull::dangling()` pointer that we use to simulate the ZST in our vector. This means we'd cause undefined behavior if we tried to deallocate something we never allocated (obviously, and for good reasons). To fix this, in our `RawVec`'s `Drop` trait, we're going to tweak it to ensure we only deallocate types that are sized.
219+
220+
```rust,ignore
221+
impl<T> Drop for RawVec<T> {
222+
fn drop(&mut self) {
223+
println!("RawVec<T> Drop called, deallocating memory");
224+
if self.cap != 0 && std::mem::size_of::<T>() > 0 {
225+
let layout = std::alloc::Layout::array::<T>(self.cap).unwrap();
226+
unsafe {
227+
std::alloc::dealloc(self.ptr.as_ptr() as *mut _, layout);
228+
}
229+
}
230+
}
231+
}
232+
```
233+

0 commit comments

Comments
 (0)