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 c34b98f
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
1 change: 1 addition & 0 deletions library/alloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
#![feature(async_closure)]
#![feature(async_fn_traits)]
#![feature(async_iterator)]
#![feature(box_uninit_write)]
#![feature(clone_to_uninit)]
#![feature(coerce_unsized)]
#![feature(const_align_of_val)]
Expand Down
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_raw(Box::write(Box::new_uninit(), ArcInner {
strong: atomic::AtomicUsize::new(1),
weak: atomic::AtomicUsize::new(1),
data: T::default(),
}));
// SAFETY: `Box::into_raw` consumes the `Box` and never returns null
unsafe { Self::from_inner(NonNull::new_unchecked(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 c34b98f

Please sign in to comment.