Why does the STL reserve an interface for Allocator?
Taking vector
as example:
template<class T,class Allocator = std::allocator<T>>
class vector;
Since there are many options for us to allocate memory and construct objects likeoperator new,delete,new[],delete[]
,which could do almost anything we need when we create an object.
So why does the STL containers like vector
need an Allocator interface,which at most time is the default std::allocator
if we don't assgin one? Why not just use the new
expressions?
If the purpose is to make user-defined allocating behaviors possible,why not just let the users provide their self-defined operator new,new[]
,etc?
allocator is the memory allocator for the STL containers. This container can separate the memory allocation and de-allocation from the initialization and destruction of their elements. Therefore, a call of vec. reserve(n) of a vector vec allocates only memory for at least n elements.
Allocators handle all the requests for allocation and deallocation of memory for a given container. The C++ Standard Library provides general-purpose allocators that are used by default, however, custom allocators may also be supplied by the programmer.
Struct std::alloc::System The default memory allocator provided by the operating system. This is based on malloc on Unix platforms and HeapAlloc on Windows, plus related functions. It can also be used directly to allocate memory independently of whatever global allocator has been selected for a Rust program.
So specific vector and change how it allocates without changing how all vectors allocate.
new
must be overridden on a per-type basis of what you are allocating, or replaced globally. std::vector<int>
and std::vector<int, some_other_allocator>
can use a different allocation strategy; in fact, the allocator can be stateful and have shared state.
A classic one is a fast stack allocator that doesn't deallocate until it goes out of scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With