Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the STL reserve an interface for Allocator?

Tags:

c++

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 like
operator 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?

like image 451
scottxiao Avatar asked Feb 16 '18 13:02

scottxiao


People also ask

What is allocator in STL?

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.

What does an allocator actually need to do?

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.

Does std :: allocator use malloc?

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.


1 Answers

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.

like image 184
Yakk - Adam Nevraumont Avatar answered Nov 14 '22 22:11

Yakk - Adam Nevraumont