Custom allocator only for one type?

I am looking at Custom Allocators which seems to do a custom allocator for the entire program.

I am wondering if it is possible to do a custom allocator only for a single type T. I want to use the default allocator for everything except for T (and even my custom allocator for T is going to use the default allocator).

1 Like

You can't set a custom allocator for allocating just one type because the GlobalAllocator and Allocator APIs are centred around allocating blocks of memory, not typed values.

If you want, you could use something like typed_arena::Arena and pass an arena reference into anything that needs to allocate these T's. That's what rustc does to let it allocate large numbers of objects and defer calling destructors until the compiler is done.

Is there anything more you can tell us about your use case? It might be that with more assumptions we can come up with a better solution.

1 Like

It sounds like you may be looking for the (currently unstable) allocator_api feature. That allows most standard memory-allocating types, such as Box and Vec to be parametrised by an instance of Allocator, and you can allocate in allocators other than the global one using functions like Box::new_in(). If you're okay with using nightly, then you could make your type a wrapper around something with an allocator parameter.


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.