Skip to content

Outline deallocation from Rc::drop since decrementing refcount usually is warmer #116232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions library/alloc/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1651,6 +1651,21 @@ impl<T: ?Sized, A: Allocator> Rc<T, A> {
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
this.ptr.as_ptr() as *const () == other.ptr.as_ptr() as *const ()
}

unsafe fn drop_dealloc(&mut self) {
unsafe {
// destroy the contained object
ptr::drop_in_place(Self::get_mut_unchecked(self));

// remove the implicit "strong weak" pointer now that we've
// destroyed the contents.
self.inner().dec_weak();

if self.inner().weak() == 0 {
self.alloc.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
}
}
}
}

impl<T: Clone, A: Allocator + Clone> Rc<T, A> {
Expand Down Expand Up @@ -2085,19 +2100,10 @@ unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Rc<T, A> {
/// drop(foo2); // Prints "dropped!"
/// ```
fn drop(&mut self) {
unsafe {
self.inner().dec_strong();
if self.inner().strong() == 0 {
// destroy the contained object
ptr::drop_in_place(Self::get_mut_unchecked(self));

// remove the implicit "strong weak" pointer now that we've
// destroyed the contents.
self.inner().dec_weak();

if self.inner().weak() == 0 {
self.alloc.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
}
self.inner().dec_strong();
if self.inner().strong() == 0 {
unsafe {
self.drop_dealloc();
}
}
}
Expand Down