Why does allocator in c++ provide specialization for type void
I notice that t开发者_如何学JAVAhe allocator in c++ provides specialization for type void. Is there any special purpose to do this? It doesn't make sense to allocate memory for void type, right?
This old Standard Librarian column by Matt Austern has a fairly thorough discussion of allocators in general, including this tidbit:
What do we do about void? Sometimes a container has to refer to void pointers, and the rebind mechanism almost gives us what we need, but not quite. It doesn't work, because we would need to write something like malloc_allocator::pointer, and we've defined malloc_allocator in such a way that instantiating it for void would be illegal. It uses sizeof(T), and it refers to T&; neither is legal when T is void. The solution is as simple as the problem: specialize malloc_allocator for void, leaving out everything except the bare minimum that we need for referring to void pointers.
malloc_allocator is the sample implementation that Austern uses in his example, but it holds true for the general case.
The allocator needs to be specialized for void
because you cannot have references to void
.
精彩评论