Drop guarantees?

In what circumstances might drop not be called? I know there’s std::mem::forget and of course a process or thread could be forcibly terminated. Are there any other situations to be aware of?

The type may be wrapped in a ManuallyDrop, although this is essentially the same effect as std::mem::forget. And along the lines of "process or thread could be forcibly terminated", someone can run a program with panic=abort - no unwinding happens, and drops will not occur.

Leaks using (A/)Rc. Be wary of global and thread local too. Std threads can outrun the program termination when not joined, so just halt in mid execution.

1 Like

static variables don’t run Drop.

1 Like

Ahh it seems std::thread::LocalKey lists some interesting cases.

1 Like

exit will not lead to drop being called, the same goes for using system calls that replace the running process with another.

1 Like

In unsafe code, destructors aren’t called when you overwrite a value with ptr::write or ptr::copy (or variants like write_bytes, copy_nonoverlapping, etc.).

Misuse of other unsafe functions like Vec::set_len can cause leaks.

And there are more safe functions that intentionally leak values:

  • Box::leak
  • Box::into_raw
  • CString::into_raw
  • Rc::into_raw
  • Arc::into_raw
2 Likes