Skip to content

Commit

Permalink
allocate before calling T::default in <Arc<T>>::default()
Browse files Browse the repository at this point in the history
Same rationale as in the previous commit.
  • Loading branch information
jwong101 committed Oct 9, 2024
1 parent 2f4ef71 commit f72c897
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
8 changes: 7 additions & 1 deletion library/alloc/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3447,7 +3447,13 @@ impl<T: Default> Default for Arc<T> {
/// assert_eq!(*x, 0);
/// ```
fn default() -> Arc<T> {
Arc::new(Default::default())
let x = Box::into_non_null(Box::write(Box::new_uninit(), ArcInner {
strong: atomic::AtomicUsize::new(1),
weak: atomic::AtomicUsize::new(1),
data: T::default(),
}));
// SAFETY: `Box::into_non_null` consumes the `Box`
unsafe { Self::from_inner(x) }
}
}

Expand Down
4 changes: 2 additions & 2 deletions tests/codegen/placement-new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ pub fn box_default_inplace() -> Box<(String, String)> {
// CHECK-LABEL: @arc_default_inplace
#[no_mangle]
pub fn arc_default_inplace() -> Arc<(String, String)> {
// CHECK: [[ALLOCA:%.*]] = alloca
// CHECK-NOT: alloca
// CHECK: [[ARC:%.*]] = {{.*}}call {{.*}}__rust_alloc(
// CHECK: call void @llvm.memcpy.p0.p0.i64(
// CHECK-NOT: call void @llvm.memcpy.p0.p0.i64(
// CHECK: ret ptr [[ARC]]
Arc::default()
}

0 comments on commit f72c897

Please sign in to comment.