I'm working through Rust By Example and am currently looking at 16.4 (Traits > Drop). In it there is an example that implements a simple TempFile. However, the comment about the Drop implementation surprised me. The comment reads:
// When TempFile is dropped:
// 1. First, the File will be automatically closed (Drop for File)
// 2. Then our drop implementation will remove the file
My interpretation of this is that when TempFile is dropped, first its field file: File will be dropped. When that happens, file.drop will run and will close the file. Only then will TempFile::drop run.
I thought that TempFile's fields would remain un-dropped until TempFile::drop finished so that it would have access to them. So my belief is that the two steps would happen in the opposite order the comment seems to be describing.
Is the comment correct and I somehow got an erroneous belief about how destruction works? Am I misinterpreting the comment? Is the comment potentially wrong?
You can consult Destructors - The Rust Reference for more details. But even without knowing the exact algorithm, one can reason that because a &mut TempFile was passed to <TempFile as Drop>::drop(), there must be a valid TempFile and therefore a valid File too.
Looks like a bug to me. The trouble here is with the fact that on most OSes it wouldn't matter (in POSIX platforms it's perfectly fine to remove file while it's open) and on Windows it wouldn't help (in theory it should be enough to close the file and then you may remove the folder, too… but that doesn't work with many crash-inducers antiviruses – and it's pretty hard to get Windows without one, these days.