I'm reading through "learn rust with entirely too many linked lists" . In chapter 2.7 the author says that "We can't drop the contents of the Box after deallocating". How can a value be deallocated after it is dropped? Wouldn't the deallocation occur in the implementation of drop or are these separate concepts?
For some context, the author is explaining why the particular implementation of a linked list is not tail recursive and thus cannot be optimised by the compiler.
Linked List:
pub struct List {
head: Link,
}
enum Link {
Empty,
More(Box<Node>),
}
struct Node {
elem: i32,
next: Link,
}
Drop implementation :
impl Drop for List {
fn drop(&mut self) {
// NOTE: you can't actually explicitly call `drop` in real Rust code;
// we're pretending to be the compiler!
self.head.drop(); // tail recursive - good!
}
}
impl Drop for Link {
fn drop(&mut self) {
match *self {
Link::Empty => {} // Done!
Link::More(ref mut boxed_node) => {
boxed_node.drop(); // tail recursive - good!
}
}
}
}
impl Drop for Box<Node> {
fn drop(&mut self) {
self.ptr.drop(); // uh oh, not tail recursive!
deallocate(self.ptr);
}
}
impl Drop for Node {
fn drop(&mut self) {
self.next.drop();
}
}