Memory pool in which the 'slices' allocated have `'static` lifetime

I'm using TypedArena's typed_arena::Arena - Rust method, which returns a reference to a slice, which is basically tied to the arena's lifetime.

Is there a memory pool crate that does the allocation but in a way that the slice lives by itself? That is, it has 'static lifetime? Obviously the arena must know about its children, but in this case I could drop the memory (it deallocated itself) or pass back to the arena manually for recycling.

There are almost no limitations on what you can do with a 'static reference - it may be copied, passed to a new thread, stored in a static somewhere, etc. because the promise of &'static _ is that the value is valid forever. So dropping the value or recycling its memory would, by definition, require the use of unsafe.

If you don't plan to drop the value or reuse its memory at all, you can simply use Box::leak.

1 Like

Your program's heap is such memory pool. Box::leak gives you 'static slices.

'static doesn't mean it lives "by itself". It means it lives until the end of the program, i.e. it's a leaked memory. This is different from <T: 'static> generic bound which is a roundabout way of forbidding types with temporary references, but doesn't actually require T to live that long.

String literals are 'static, because they live in the executable loaded into memory until the end of the program, and you can't free them until the program quits, so they're pretty much equivalent of leaked memory.

Instead of &'static [T] you probably want Box<[T]> which is the actual type that lives "by itself", i.e. as long as needed, but no longer.

1 Like

Related things you might find useful: bumpalo::boxed::Box is like what you describe, except that bumpalo doesn't reuse freed memory; slotmap and generational-arena allow deletion with memory reuse and Copy handles (much like &'static _) but with a kind of different API.

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.