Search code examples
rustmemory-management

Is there a C++ polymorphic memory resource equivalent in Rust?


New to Rust, and I've been enjoying it, but the one thing I havn't figured out yet is how to reproduce C++'s polymorphic memory resource.

In my own C++ applications this gives me a lot of nice capabilities, but mainly I like:

There are other use cases- like metrics, shared memory, high-bandwidth memory, etc... but they are less important.

Is this even feasible in Rust?

Allocators seem to be a part of the type using generics. Or the recommendation is to override the global memory allocator. These both don't seem flexible enough to do what I want.

I did find an "allocator-api" experimental feature. Am I just waiting for this?


Solution

  • Currently being "allocator-generic" is unsolved problem in Rust. Experimental feature allocator_api looks like something that Rust might end up with, but it has been unstable for some time and I don't think it is going to be stabilised any time soon (mainly because there is no consensus, that this is the way it should be done).

    So for now Allocator trait is unstable and some containers/collections in standard library are generic over an allocator (defaulting to GlobalAllocator), and have unstable methods that allow interacting with it.

    If you would like to use something like this, you can either switch to a nightly compiler and use unstable feature, or you might try using allocator-api2 crate, which mirrors allocator traits in the standard library, and once those are stabilised, it will re-export them (something similar to how futures crate defined Future trait before it was stabilised).

    Either way you won't find many support for custom allocators in the crates ecosystem, but I you are willing to implement your own collections, then this should probably give you similar experience to that from C++.