Why does the STL reserve an interface for Allocator?

Why does the STL reserve an interface for Allocator? Taking vectoras an example:

template<class T,class Allocator = std::allocator<T>> 
class vector;

Since there are many options for allocating memory and constructing objects, for example, operator new,delete,new[],delete[]which can do almost everything we need when we create an object.
So, why do STL containers, such as vector, need the Allocator interface, which in most cases is the default std::allocatorby default if we don't capsize it? Why not just use expressions new?
If the goal is to make user-defined distribution options possible, why not just let users provide their self-defined operator new,new[], etc.

+6
source share
2 answers

So change a specific vector and how it selects without changing how all the vectors are distributed.

newmust be redefined based on each type of what you assign or replace globally. std::vector<int>and std::vector<int, some_other_allocator>may use a different distribution strategy; in fact, the dispenser can be stateless and have a common state.

Classic is a fast stack dispenser that is not freed until it goes beyond.

+11
source

For example, std::list<T, Allocator>also provides this interface. You are usually told not to use linked lists due to poor cache locality.

, , , , std::list

#include <boost/pool/pool_alloc.hpp>

template <typename T>
using pooled_list = std::list<T, boost::pool_allocator<T>>

std::list. . std::char_traits std::basic_string.

+1

All Articles