Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 51f5813

Browse files
committedSep 28, 2023
Outline deallocation from Rc::drop since decrementing refcount usually is warmer
1 parent b9dd2ce commit 51f5813

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed
 

‎library/alloc/src/rc.rs

+19-13
Original file line numberDiff line numberDiff line change
@@ -1651,6 +1651,21 @@ impl<T: ?Sized, A: Allocator> Rc<T, A> {
16511651
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
16521652
this.ptr.as_ptr() as *const () == other.ptr.as_ptr() as *const ()
16531653
}
1654+
1655+
unsafe fn drop_dealloc(&mut self) {
1656+
unsafe {
1657+
// destroy the contained object
1658+
ptr::drop_in_place(Self::get_mut_unchecked(self));
1659+
1660+
// remove the implicit "strong weak" pointer now that we've
1661+
// destroyed the contents.
1662+
self.inner().dec_weak();
1663+
1664+
if self.inner().weak() == 0 {
1665+
self.alloc.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1666+
}
1667+
}
1668+
}
16541669
}
16551670

16561671
impl<T: Clone, A: Allocator + Clone> Rc<T, A> {
@@ -2085,19 +2100,10 @@ unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Rc<T, A> {
20852100
/// drop(foo2); // Prints "dropped!"
20862101
/// ```
20872102
fn drop(&mut self) {
2088-
unsafe {
2089-
self.inner().dec_strong();
2090-
if self.inner().strong() == 0 {
2091-
// destroy the contained object
2092-
ptr::drop_in_place(Self::get_mut_unchecked(self));
2093-
2094-
// remove the implicit "strong weak" pointer now that we've
2095-
// destroyed the contents.
2096-
self.inner().dec_weak();
2097-
2098-
if self.inner().weak() == 0 {
2099-
self.alloc.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
2100-
}
2103+
self.inner().dec_strong();
2104+
if self.inner().strong() == 0 {
2105+
unsafe {
2106+
self.drop_dealloc();
21012107
}
21022108
}
21032109
}

0 commit comments

Comments
 (0)
Please sign in to comment.