Question

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);
    }
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top