Skip to content

Commit d706539

Browse files
bors[bot]Enselic
andauthored
Merge #214
214: Explain safety of `unsync::OnceCell::get(&self)` in more detail r=matklad a=Enselic Background: I'm working on improving my unsafe Rust skills, and figuring out how `once_cell` works is one way to do that. By more elaborately explaining why `unsync::OnceCell::get(&self)` is safely implemented, I hope to help others increase their understanding of unsafe Rust as well. (It was not obvious to me at first why `unsync::OnceCell::get(&self)` was safe. But I think I figured it out now.) Co-authored-by: Martin Nordholts <[email protected]>
2 parents af9d29c + cc07949 commit d706539

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

src/lib.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,10 @@ pub mod unsync {
454454
/// Returns `None` if the cell is empty.
455455
#[inline]
456456
pub fn get(&self) -> Option<&T> {
457-
// Safe due to `inner`'s invariant
457+
// Safe due to `inner`'s invariant of being written to at most once.
458+
// Had multiple writes to `inner` been allowed, a reference to the
459+
// value we return now would become dangling by a write of a
460+
// different value later.
458461
unsafe { &*self.inner.get() }.as_ref()
459462
}
460463

0 commit comments

Comments
 (0)