Automatic Drop is bad; Why?

In Learning Rust with Entirely Too Many Lists, drop-subsection is
is mentioned that the automatic drop is bad.

But this point is never revisited or made more clear.
Does anyone know of an explanation? Or a "fix"?

The badness is this context is described just after:

When list gets dropped, it will try to drop A, which will try to drop B, which will try to drop C. Some of you might rightly be getting nervous. This is recursive code, and recursive code can blow the stack!

A better word here might be "naive" or "suboptimal."

"Bad" here refers not to the idea of an automatic drop, but the implementation of the drop. (Or, perhaps, the drop (emitted automatically) is bad, not necessarily the fact that it's automatic.)

4 Likes

In the context of lists (and big graph data structures), the issue is that a naive drop implementation is expensive, since it drops elements one by one, depth-first. A hand-written drop function could possibly traverse such structures in a loop or with lower stack usage.

Apart from that, Drop is dangerous in for unsafe code in Rust. For example, it's easy to forget that writes through pointers will drop the previous value, so *pointer = value will crash if the pointer pointed to uninitialized memory (ptr::write exists to avoid this).

But overall automatic Drop does a lot of good things in Rust. It simplifies memory management, prevents double-free, prevents most leaks, makes guard pattern possible, etc.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.