开发者

what does allocator mean in STL

I'm using list class in c++ and i don't know what 开发者_StackOverflow中文版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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜