简体   繁体   中英

what does allocator mean in STL

I'm using list class in c++ and i don't know what does allocator mean here

template < class T, class Allocator = allocator<T> > class list;

if i have list <int> mylist would it mean allocate integer type of memory using the allocator when an element is added to list? and when do you want a custom allocator?

Yes. An allocator is a way of factoring the allocation of memory from the use of memory. If a container needs some memory, instead of:

// too rigid, cannot allow custom allocation schemes
void* mem = ::operator new(someAmount);

You get:

// flexible, allows custom allocation schemes
void* mem = myallocator.allocate(someAmount);

There is a standard allocator, std::allocator , which uses global operator new and operator delete .

You want to use your own allocator anytime you need to allocate in a special way. These cases may be: get memory from some freelist, allocate from the stack, etc. (Generally for optimization purposes, though you could also record statistics with a custom allocator) Most of the time, the standard allocator works perfectly.

In addition to what GMan pointed out, custom allocators can be used for aligned memory allocation. Some high performance libraries which use SIMD instruction set require aligned memory. Those libraries may provide you with ready to use allocators which you can plug into any STL container. There are also cache aligned allocators to avoid false sharing in multi-threaded code. Intel's TBB comes with scalable allocators, which can speed up multi-threaded memory allocation/delocation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM