Box with a custom Deleter?

I have a situation in which I want to create a Box<[T]> but the layout of the allocation has some extra metadata at the beginning.

I realize, this could Just Work like it would in C++'s unique_ptr if I was able to customize the Drop strategy used by Box.

Will Rust ever have some kind of functionality like this in the future?

Maybe you could create a wrapper type around your allocation (say Array<T>) and implement Drop and Deref<Target=[T]> for it and use an Array<T> instead of a Box<[T]>.
Does that special allocation come from Rust btw? Because I think you cannot have Rust free it if it was created by (for example) a C allocator.


If you want to customize allocation and deallocation of the box, use your own box-like type.


Nah, it's internal to Rust. I'm working on a Vec-like type and I noticed that Vec supports into_boxed_slice() which I'll be able unable to implement, unfortunately.

Well, I suppose I can't argue with that.

Still, there might be utility in Box someday supporting extra Drop logic. Or maybe when the Allocators WG produces more facilities.

The idiomatic way to tweak how something is destroyed in Rust is to implement your own destructor. Allowing both a custom deleter and a Drop impl sounds like a great way to confuse people, so I'd go with either a custom smart pointer or use a wrapper around the [T] that implements Deref.

1 Like

Why not map the metadata inside the box with Box<(Head, [Tail])>? If you used the global allocator, then deallocation would work out of the box.

1 Like

How do you go about constructing one of those? There are helpers to produce Box<[T]>, but it’s not obvious to me how to build the slice inside a tuple.

There aren't really any good ways. Afaik, currently the only way is to make a Box<(Head, [Tail; n])> for some n and then just coerce it. Additionally, you can't do it with tuples, but you can with a struct:

struct WithHeader<Arr: ?Sized> {
    header: u32,
    arr: Arr,

fn b(b: Box<WithHeader<[u8; 10]>>) -> Box<WithHeader<[u8]>> {

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.