Can a memory pool allocate things with a `'static` lifetime?

I was looking at

impl FreeList<'static, HeapAllocator> {
    //fn new(...)

impl<'a, A: 'a + Allocator> Allocator for FreeList<'a, A> {
    fn allocate<T>(&self, val: T) -> Result<AllocBox<T, Self>, (Error, T)> where Self: Sized

for the 'static case, AllocBox<T, Self> is also 'static (because Self is 'static), which means that the allocated memory and the allocator are independent (one does not contain a reference to the other). Which means that if the allocator is dropped, the memory can still live. How is it possible? Shouldn't the allocated memory keep a reference to the memory pool so it knows where to go back once it's dropped?

Can someone give me an example of a memory pool in Rust that allocates with 'static lifetime? I think this is one example, but it's not maintained since 2017.

There's a lifetime that's not shown in that rendition of the docs -- AllocBox<'a, T, A>, and in modern rustdoc it will indicate AllocBox<'_, T, A> for the elided lifetime. In fn allocation, the elided lifetimes are connected between input and output, so the only way it can return AllocBox<'static, T, A> is if it were called with &'static self. The existence of such a reference means the actual Self (FreeList) can never be dropped.


To add to this, that's effectively the same as leaking memory, which for most use cases is undesirable.

For those few cases where leaking is acceptable, given the above you might as well just use Box::leak() to obtain the &'static mut T since it's likely to perform less work than a full-blown allocator.

I'm still confused.

FreeList claims to reuse memory, but when its allocated memory is dropped: allocators/ at master · rphmeier/allocators · GitHub it does not put the AllocBox back into the FreeList.

So my question remains: is it possible to have a memory pool in rust that recycles memory but allocates it with a 'static lifetime?

It would be possible if either the memory pool itself or the memory it allocates is leaked, in any case.


It calls self.allocator.deallocate_raw, which does put the block back in the free_list.

The global allocator is an example of this. Or are you looking for something more specialized?

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.