diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 942b2b9d2dadf..f46b9f9d67db5 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -4256,12 +4256,15 @@ unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_default", issue = "143894")] -impl const Default for Vec { - /// Creates an empty `Vec`. +impl const Default for Vec +where + A: Allocator + [const] Default, +{ + /// Creates an empty `Vec` in the allocator `A`. /// /// The vector will not allocate until elements are pushed onto it. - fn default() -> Vec { - Vec::new() + fn default() -> Self { + Vec::new_in(A::default()) } } diff --git a/library/alloctests/tests/lib.rs b/library/alloctests/tests/lib.rs index 699a5010282b0..b25e0ea601ff5 100644 --- a/library/alloctests/tests/lib.rs +++ b/library/alloctests/tests/lib.rs @@ -41,6 +41,7 @@ #![feature(macro_metavar_expr_concat)] #![feature(vec_peek_mut)] #![feature(vec_try_remove)] +#![feature(const_default)] #![allow(internal_features)] #![deny(fuzzy_provenance_casts)] #![deny(unsafe_op_in_unsafe_fn)] diff --git a/library/alloctests/tests/vec.rs b/library/alloctests/tests/vec.rs index db7da0db47d74..c98faea07ae02 100644 --- a/library/alloctests/tests/vec.rs +++ b/library/alloctests/tests/vec.rs @@ -1104,6 +1104,33 @@ fn test_into_iter_drop_allocator() { assert_eq!(drop_count, 2); } +#[test] +fn test_default_vec_in_custom_allocator() { + struct ReferenceCountedAllocator; + + impl const Default for ReferenceCountedAllocator { + fn default() -> Self { + Self {} + } + } + + unsafe impl Allocator for ReferenceCountedAllocator { + fn allocate(&self, layout: Layout) -> Result, core::alloc::AllocError> { + System.allocate(layout) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // Safety: Invariants passed to caller. + unsafe { System.deallocate(ptr, layout) } + } + } + + let mut vec = Vec::::default(); + + vec.push(10); + assert_eq!(vec.len(), 1); +} + #[test] fn test_into_iter_zst() { #[derive(Debug, Clone)]