You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Consider this code, which implements a construct similar to Arc, but points to the stack, and will abort the program if you try to deallocate the backing allocation while there are still outstanding references.
The parts of the code that is relevant to the question is as follows:
The Storage type has public methods that effectively hands out &T references to the data inside, but with an unbound lifetime. To make this sound, the Drop impl of StorageGuard checks whether there are any outstanding references to the data, and will abort the program if there are.
The destructor of Storage<T> consists of two steps:
Call <StorageGuard as Drop>::drop().
Call <T as Drop>::drop().
Note that step 1 checks whether there are any &T references, and step 2 creates a &mut T that would potentially alias with any such references. Therefore, this unsafe code assumes that the &mut T is only created on step 2. Note that &mut Storage<T> is never created, since Storage doesn't implement Drop.
Is it OK for unsafe code to assume that the destructor will never create any &mut T references until the point where Drop::drop is called?
The text was updated successfully, but these errors were encountered:
theemathas
changed the title
Will destructors only create &mut references when Drop is implemented?
Will destructors create &mut references only when Drop::drop() is called?
Oct 30, 2024
Consider this code, which implements a construct similar to
Arc
, but points to the stack, and will abort the program if you try to deallocate the backing allocation while there are still outstanding references.The parts of the code that is relevant to the question is as follows:
The
Storage
type has public methods that effectively hands out&T
references to the data inside, but with an unbound lifetime. To make this sound, theDrop
impl ofStorageGuard
checks whether there are any outstanding references to the data, and will abort the program if there are.The destructor of
Storage<T>
consists of two steps:<StorageGuard as Drop>::drop()
.<T as Drop>::drop()
.Note that step 1 checks whether there are any
&T
references, and step 2 creates a&mut T
that would potentially alias with any such references. Therefore, this unsafe code assumes that the&mut T
is only created on step 2. Note that&mut Storage<T>
is never created, sinceStorage
doesn't implementDrop
.Is it OK for unsafe code to assume that the destructor will never create any
&mut T
references until the point whereDrop::drop
is called?The text was updated successfully, but these errors were encountered: