File tree 1 file changed +14
-1
lines changed
1 file changed +14
-1
lines changed Original file line number Diff line number Diff line change @@ -1689,7 +1689,20 @@ impl<T: Default> Default for Box<T> {
1689
1689
/// Creates a `Box<T>`, with the `Default` value for T.
1690
1690
#[ inline]
1691
1691
fn default ( ) -> Self {
1692
- Box :: write ( Box :: new_uninit ( ) , T :: default ( ) )
1692
+ let mut x: Box < mem:: MaybeUninit < T > > = Box :: new_uninit ( ) ;
1693
+ unsafe {
1694
+ // SAFETY: `x` is valid for writing and has the same layout as `T`.
1695
+ // If `T::default()` panics, dropping `x` will just deallocate the Box as `MaybeUninit<T>`
1696
+ // does not have a destructor.
1697
+ //
1698
+ // We use `ptr::write` as `MaybeUninit::write` creates
1699
+ // extra stack copies of `T` in debug mode.
1700
+ //
1701
+ // See https://github.com/rust-lang/rust/issues/136043 for more context.
1702
+ ptr:: write ( & raw mut * x as * mut T , T :: default ( ) ) ;
1703
+ // SAFETY: `x` was just initialized above.
1704
+ x. assume_init ( )
1705
+ }
1693
1706
}
1694
1707
}
1695
1708
You can’t perform that action at this time.
0 commit comments