File tree Expand file tree Collapse file tree 1 file changed +14
-1
lines changed Expand file tree Collapse file tree 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> {
16891689 /// Creates a `Box<T>`, with the `Default` value for T.
16901690 #[ inline]
16911691 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+ }
16931706 }
16941707}
16951708
You can’t perform that action at this time.
0 commit comments