Open
Description
I tried this code:
#![feature(btreemap_alloc)]
#![feature(allocator_api)]
use std::collections::BTreeMap;
use std::sync::Arc;
use std::alloc::Allocator;
use std::ptr::{self, NonNull};
#[derive(Clone)]
pub struct AllocWrapper<T>(pub Arc<T>);
unsafe impl<T: Allocator> Allocator for AllocWrapper<T> {
fn allocate(
&self,
layout: std::alloc::Layout,
) -> Result<std::ptr::NonNull<[u8]>, std::alloc::AllocError> {
self.0.allocate(layout)
}
unsafe fn deallocate(&self, ptr: std::ptr::NonNull<u8>, layout: std::alloc::Layout) {
self.0.deallocate(ptr, layout)
}
fn allocate_zeroed(
&self,
layout: std::alloc::Layout,
) -> Result<std::ptr::NonNull<[u8]>, std::alloc::AllocError> {
self.0.allocate_zeroed(layout)
}
unsafe fn grow(
&self,
ptr: std::ptr::NonNull<u8>,
old_layout: std::alloc::Layout,
new_layout: std::alloc::Layout,
) -> Result<std::ptr::NonNull<[u8]>, std::alloc::AllocError> {
self.0.grow(ptr, old_layout, new_layout)
}
unsafe fn grow_zeroed(
&self,
ptr: std::ptr::NonNull<u8>,
old_layout: std::alloc::Layout,
new_layout: std::alloc::Layout,
) -> Result<std::ptr::NonNull<[u8]>, std::alloc::AllocError> {
self.0.grow_zeroed(ptr, old_layout, new_layout)
}
unsafe fn shrink(
&self,
ptr: std::ptr::NonNull<u8>,
old_layout: std::alloc::Layout,
new_layout: std::alloc::Layout,
) -> Result<std::ptr::NonNull<[u8]>, std::alloc::AllocError> {
self.0.shrink(ptr, old_layout, new_layout)
}
}
fn main() {
let allocator = AllocWrapper(Arc::new(std::alloc::System));
println!("count = {}", Arc::strong_count(&allocator.0));
let x = Box::new_in(5, allocator.clone());
println!("count = {}", Arc::strong_count(&allocator.0));
let _ = NonNull::from(Box::leak(x));
println!("count = {}", Arc::strong_count(&allocator.0));
}
I expected to see this happen:
- When the
x
get dropped, the ref count decreased to 1
Instead, this happened:
- When the
x
get dropped, the ref count dose not change
The current implementation of Box::leak
will ManuallyDrop
the whole Box
but only leak the data pointer. The destruction function of the allocator will not be called. I'm not sure if it the expected behavior.
pub const fn leak<'a>(b: Self) -> &'a mut T
where
A: 'a,
{
unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
}
Meta
rustc --version --verbose
:
rustc 1.68.0-nightly (bdb07a8ec 2022-12-11)
binary: rustc
commit-hash: bdb07a8ec8e77aa10fb84fae1d4ff71c21180bb4
commit-date: 2022-12-11
host: aarch64-apple-darwin
release: 1.68.0-nightly
LLVM version: 15.0.6
Backtrace
<backtrace>
related to : #106203