Hello everyone,
I would like to ask a question about dropping values in Rust (when the drop
method in the Drop
trait is automatically called) and I would appreciate if you could kindly make some clarification.
When I read the chapter 4 of The Book, about borrowing and ownership, I understood that once a value is being dropped, it is finished. For me from a C programming point of view, a call to the free()
function allows to free the space allocated by a previous call to the malloc()
function.
So when I read the chapter 4 of The Book, I thought that the drop
method is a similar concept but in a more robust way thanks to the borrowing rules. But the ultimate goal is the same, that is, freeing resources ( = memory). Therefore I had understood (and apparently misunderstood) that :
A variable has been dropped in Rust = its allocated memory has been released
However, when I read the chapter 15 of The Book about smart pointers, I read for the first time about the Weak
pointer. Here is what we can read in the module documentation of Rc smart pointer : std::rc
The
downgrade
method can be used to create a non-owningWeak
pointer. AWeak
pointer can beupgrade
d to anRc
, but this will returnNone
if the value stored in the allocation has already been dropped. In other words,Weak
pointers do not keep the value inside the allocation alive; however, they do keep the allocation (the backing store for the inner value) alive.
I think I'm completely confused by the last statement that I indicated in bold in the above mentioned quote. Based on this definition (or I should rather say what I understand from it), we can have a dropped value whereas its allocated memory is still valid for that value.
Therefore, my question is, what happens exactly when the drop()
method is called? Is it just a some kind of mark put on a value at runtime so that it cannot be used anymore or is it actually releasing the allocated memory which leads to the total destruction of that value?
Thanks in advance