STL allocator
wanweibaike STL allocator
In C++ computer programming, allocators are a component of the C++ Standard Library. The standard library provides several data structures, such as list and set, commonly referred to as containers. A common trait among these containers is their ability to change size during the execution of the program. To achieve this, some form of dynamic memory allocation is usually required. 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.
NOTE:
1、STL采用的是policy-based design: 将allocator作为container的template parameter
Custom allocators
One of the main reasons for writing a custom allocator is performance. Utilizing a specialized custom allocator may substantially improve the performance or memory usage, or both, of the program.[4][15] The default allocator uses operator new
to allocate memory.[16] This is often implemented as a thin layer around the C heap allocation functions,[17] which are usually optimized for infrequent allocation of large memory blocks. This approach may work well with containers that mostly allocate large chunks of memory, like vector and deque.[15] However, for containers that require frequent allocations of small objects, such as map and list, using the default allocator is generally slow.[4][17] Other common problems with a malloc-based allocator include poor locality of reference,[4] and excessive memory fragmentation.[4][17]
Usage
When instantiating one of the standard containers, the allocator is specified through a template argument, which defaults to std::allocator<T>
:[20]
namespace std {
template <class T, class Allocator = allocator<T> > class vector;
// ...
NOTE:
policy-based design
cppreference Dynamic memory management # Allocators
Allocators are class templates encapsulating memory allocation strategy. This allows generic containers to decouple memory management from the data itself.
NOTE:
一、decouple解耦
二、这些allocator的实现,最终都是依赖于new operator