Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::allocator<>::deallocate() have a size_type parameter which is not used?

When using an std::allocator, the deallocate function requires a pointer argument, and a size_type argument (std::allocator<>::deallocate(std::allocator<>::pointer p, std::allocator<>::size_type). However, the size_type is not used, and is not optional either. So why is it there? It really confuses me, as it should be optional, or even not there, because it is not used in the function.

Edit: MSVC's implementation of allocator deallocate

void deallocate(pointer _Ptr, size_type)
    {   // deallocate object at _Ptr, ignore size
    ::operator delete(_Ptr);
    }
like image 857
Joseph Avatar asked Mar 01 '14 11:03

Joseph


1 Answers

Even if the standard allocator does not use the size of the memory block that is to be freed, other allocators might. Therefore, the argument has to be there such that all STL code that uses allocators can use different allocators in the same way.

The standard allocator does not need the size argument because it remembers the size of each allocated block. However, this adds quite a bit of overhead to each allocation.

If the user of the allocator knows how large each block of memory is (this is very often the case), then one can use a custom allocator which saves this overhead, and tell the deallocate function about the size of the block instead.

like image 121
Frank Avatar answered Sep 21 '22 07:09

Frank