What is an Allocator?

And so our test function is expecting this parameter to be a template class with 2 parameters, value type and allocator type.Line 10: The macro __PRETTY_FUCNTION__ is available in GCC and CLang..It gives us the name of the function in a pretty pretty format, including the template parameters, which we especially want.Line 12: Here we create a container of int-s with our my::Allocator.Line 14: This is the generic, container independent way of adding an element into an STL container.But there is a problem, and this code won’t compile..As stated above, our test function is expecting the ContainerT template parameter to be a template class with 2 parameters..The vector and list are such types, whereas the set is not..It has 3 parameters:template <typename T, typename CompareT = std::less<T>, typename AllocatorT = std::allocator<T> >class set;As a workaround, we can define a type alias:Line 19–20: This type alias has only two template parameters, just like vector and list.Finally, it compiles..And prints this:It didn’t work..After debugging it’s easy to see that our shadowing functions are never being called..In fact, after a little more debugging it turns out that containers carry an instance of std::allocator instead of my::Allocator.This happens because allocators are supposed to be so-called rebindable family types..This means, that even though std::allocator<T> and std::allocator<U> are completely different types, one is representable in the other..That’s why std::allocator has such a constructor:template <typename U>allocator(const allocator<U>& other);But why is there such a heavy requirement on such a “useful” type?.That’s because most of the STL containers force us to provide a specialized allocator type, like my::Allocator<int>, whereas they really need the first my::Allocator part only..We create an object, let’s say, of type std::vector<int, std::allocator<int> >, and we think the allocator instance in it is of type std::allocator<int>, whereas it is std::allocator<WHATEVER_I_WANT___TRUST_ME__I_KNOW_BETTER>.. More details

Leave a Reply